webdriver 模拟浏览器行为

rich web的测试需要模拟用户的交互较多, 所以只用http协议简单的来实现web的行为并不能很好对GUI进行测试. 不过现在自动化测试技术,似乎对GUI并没有很大的热情, 因为GUI经常变化, 导致gui的自动化测试脚本也经常需要维护, 维护的时间有时大大超过了开发的时间. 不断地gui需求变化, 导致自动化测试人员疲于奔命.

当然这里我们不谈自动化测试. 因为最近想做一个web 爬虫, 但是需要有java script的引擎. 即需要真实模拟浏览器的解析js并展现. 然后将dom 及 content 获取到. 所以,就去找带js 解析引擎的库. 其实直接使用浏览器内核也可以,但是难度不小. 有了webdriver 使用起来则方便的多.

除了webdriver, 应该还有其他的解决方案. 如下可以请同学们也作为参考.

1. 各种开源的浏览器内核了, 例如webkit

2. Ruby语言的 Capybara 测试javascript的引擎

3. htmlunit (备注, webdriver 基于 htmlunit, 而htmlunit 基于rhino)

好了, 那我们开始进入webdriver 吧. ~~~

一 下载 selenium-java-2.35.0.zip

http://code.google.com/p/selenium/downloads/detail?name=selenium-java-2.35.0.zip&can=2&q=

二 解压

三 新建一个java 工程 (记住一定要有java 1.6 及以上的jdk )

四 在java 工程里创建lib文件夹, 把第二步解压得jar 都拷贝进来。

然后, 在eclipse 里, 把所有的jar 都加到buildpath里。

五。 新建一个package com.whoistester.webcrawler

六 新建一个class文件

package com.whoistester.webcrawler;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Test {

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

System.out.println(driver.getWindowHandle());
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
}

}

七 执行该例子

此篇文章已被阅读3564 次

Add a Comment

邮箱地址不会被公开。 必填项已用*标注