优点:HtmlUnitDriver不会实际打开浏览器,运行速度很快。对于用FireFox等浏览器来做测试的自动化测试用例,运行速度通常很慢,HtmlUnitDriver无疑是可以很好地解决这个问题。
缺点:它对JavaScript的支持不够好,当页面上有复杂JavaScript时,经常会捕获不到页面元素。
1.使用HtmlUnitDriver访问百度,并返回页面标题信息
package selenium.test.googleSearch;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class BaiduHtmlUnitDriver {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver=new HtmlUnitDriver();
//打开百度首页
driver.get("http://www.baidu.com/");
//打印页面标题
System.out.println("页面标题:"+driver.getTitle());
//根据id获取页面元素输入框
WebElement search=driver.findElement(By.id("kw"));
//在id=“kw”的输入框输入“selenium”
search.sendKeys("selenium");
//根据id获取提交按钮
WebElement submit=driver.findElement(By.id("su"));
//点击按钮查询
submit.click();
//打印当前页面标题
System.out.println("页面标题:"+driver.getTitle());
//返回当前页面的url
System.out.println("页面url:"+driver.getCurrentUrl());
//返回当前的浏览器的窗口句柄
System.out.println("窗口句柄:"+driver.getWindowHandle());
}
}
2.selenium官网wiki中关于HtmlUnitDriver的例子
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example {
public static void main(String[] args) {
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new HtmlUnitDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
}
}
分享到:
相关推荐
HtmlUnitDriver HtmlUnitDriver是适用于无头浏览器的WebDriver兼容驱动程序。 消息 下载及安装 Maven / Gradle / ... 添加对Maven Central中可用的最新htmlunit-driver版本的依赖关系,请注意,更改了artifactId和...
赠送jar包:htmlunit-driver-2.49.1.jar; 赠送原API文档:htmlunit-driver-2.49.1-javadoc.jar; 赠送源代码:htmlunit-driver-2.49.1-sources.jar; 赠送Maven依赖信息文件:htmlunit-driver-2.49.1.pom;...
赠送jar包:htmlunit-driver-2.49.1.jar; 赠送原API文档:htmlunit-driver-2.49.1-javadoc.jar; 赠送源代码:htmlunit-driver-2.49.1-sources.jar; 赠送Maven依赖信息文件:htmlunit-driver-2.49.1.pom;...
import org.openqa.selenium.htmlunit.HtmlUnitDriver; import static junit.framework.Assert.assertNotNull; public class WebDriverTest { private WebDriver page; @Before public void before...
WebDriver针对各个浏览器而开发,取代了嵌入到被测...它还包括一个基于HtmlUnit的无界面实现,称为HtmlUnitDriver。WebDriver API可以通过Python、Ruby、Java和C#访问,支持开发人员使用他们偏爱的编程语言来创建测试。