【发布时间】:2015-06-12 09:19:46
【问题描述】:
我正在尝试遵循 Selenium Webdrive 教程
http://www.toolsqa.com/selenium-webdriver/headless-browser-testing-selenium-webdriver/
有一个简单的测试,步骤如下:
获取页面标题。
搜索“硒”
再次检查页面标题。
从类代码示例开始,这里是我的代码
package headlessBrowser;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class TestOne {
public static void main(String[] args) {
// Declaring and initialising the HtmlUnitWebDriver
HtmlUnitDriver unitDriver = new HtmlUnitDriver();
// open google.com webpage
unitDriver.get("http://google.com");
System.out.println("Title of the page is -> " + unitDriver.getTitle());
// find the search edit box on the google page
WebElement searchBox = unitDriver.findElement(By.name("q"));
// type in Selenium
searchBox.sendKeys("Selenium");
// find the search button
WebElement button = unitDriver.findElement(By.name("gbqfba"));
// Click the button
button.click();
System.out.println("Title of the page is -> " + unitDriver.getTitle());
}
}
尝试执行它我有以下错误
Title of the page is ->
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element with name: q
没有打印页面名称:????? 似乎找不到页面中的“q”元素。 ????
我检查过 Firebug,似乎代码中有“q”元素(在下面的代码片段中查找 name="q" ...)
<input spellcheck="false" dir="ltr" style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; background: transparent url("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D") repeat scroll 0% 0%; position: absolute; z-index: 6; left: 0px; outline: medium none;" aria-autocomplete="both" role="combobox" aria-haspopup="false" class="gsfi" id="lst-ib" maxlength="2048" name="q" autocomplete="off" title="Cerca" value="" aria-label="Cerca" type="text">
我在 Windows 7 上使用 Eclipse Luna
有什么建议吗?提前谢谢你...
切萨雷
【问题讨论】:
-
您需要使用 HtmlUnitDriver 和 Firefox 或 Chrome 功能并打开 Javascript。
-
uhmmmm .... 我尝试添加“unitDriver.setJavascriptEnabled(true);”到我的代码,但它仍然不起作用....
-
上面的代码对我来说工作正常。刚刚将“gbqfba”改为“btnG”。
标签: java selenium selenium-webdriver webdriver headless-browser