硒:找到正确的元素标识符

时间:2018-11-21 15:51:02

标签: vb.net selenium selenium-chromedriver

我对硒自动化比较陌生,正在尝试测试为我创建的表单。我想将测试值放入文本框,其HTML代码如下:

<input type="text" id="txtEndCustId" onkeypress="return isNumberKey(event);" class="Text" required="" onfocus="txtEndCustIdFocus('Your customer END CUSTOMER DEP ID');" onblur="txtEndCustIdblur();">

我以为我会用盒子的“ id”,但是代码:

Dim options As New Chrome.ChromeOptions
Dim service As ChromeDriverService = ChromeDriverService.CreateDefaultService

Dim wd As New Chrome.ChromeDriver(service, options)

wd.Navigate.GoToUrl("x")
wd.FindElementById("txtEndCustId").SendKeys("1")

给出错误:

Unable to locate element: {"method":"id","selector":"txtEndCustId"}

老实说,我不知道我在哪里出错了-预先感谢您的帮助。

是否有任何“列出所有元素ID”功能,以便我可以将它们与chrome inspector视图中显示的内容结合使用?

1 个答案:

答案 0 :(得分:1)

由于您的元素位于框架内,因此您需要先将驱动程序导航到该框架,框架具有自己的文档,其中包含x个DOM元素。

首先切换到框架:

//You need to use method switchTo() to set the driver to the frame document
//In this case we are passing in the id of the iframe
wd.switchTo().frame("ctl00_CPH_iframeCat");

//Now that the driver is working on the frame document, you should be able to manipulate the
//input you want
wd.FindElementById("txtEndCustId").SendKeys("1")

//Finally, switch the driver back to the main page document (original document which contains the frames)
driver.switchTo().defaultContent();

这是一个很好的文档,应对此做更详细的说明: (http://www.assertselenium.com/webdriver/handling-iframes-using-webdriver/