我在Java中使用Chrome驱动程序和Selenium。
这是在我的Java代码上。在我感兴趣的特定页面上执行该命令。
driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys("John");
这是在网站上的该特定页面上。
<input type="text" id="fname" name="firstName" placeholder="First Name" data-reactid="....">
问题甚至不在于将文本设置为输入,而是根本找不到输入字段。这是错误
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name='firstName']"}
Command duration or timeout: 20.04 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
从错误中您可以看到,我隐式等待了20秒,并且可以看到页面和字段在这段时间内已经加载。
因此,很奇怪的是,当我打开chrome并检查元素并通过xPath搜索时,可以使用相同的确切命令找到该字段(在我的Java崩溃于同一chrome窗口的同一页面上)。我可以从输入字段中找到所有其他元素。
有什么办法解决这个问题吗?硒不支持这种方式的输入字段吗?我不确定要承担什么,任何想法都将不胜感激!
最佳答案
您需要处理iframe才能访问您的元素:
// This way allows you to select an iframe using 'By' and access it.
driver.switchTo().frame(driver.findElement(By.id("frameId")));
// Now you can only handle the iframe elements, like your request
driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys("John");
// After execute all that you need inside the iframe,
// returns you to default html, outside the iframe.
driver.switchTo().defaultContent();