三、HtmlUnitDriver

优点:HtmlUnitDriver不会实际打开浏览器,运行速度很快。对于用FireFox等浏览器来做测试的自动化测试用例,运行速度通常很慢,HtmlUnitDriver无疑是可以很好地解决这个问题。
缺点:它对JavaScript的支持不够好,当页面上有复杂JavaScript时,经常会捕获不到页面元素。
[b]1.使用HtmlUnitDriver访问百度,并返回页面标题信息[/b]

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());

}

}


[b]2.selenium官网wiki中关于HtmlUnitDriver的例子[/b]

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());
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值