编写不易,转载请注明(http://shihlei.iteye.com/blog/2067716)!
一概述
获取动态资源,可以使用HtmlUnit,但是其对JS的支持还是不够完善。相对与HtmlUnit还有一种驱动浏览器的下载还原工具Selenium。可以打开浏览器,获取网页,下载解析,支持dom,js,解析效果更好,但是打开浏览器速度方面有一定损失。个人实验,禁用CSS,图片下载,速度还尚可。
Selenium也是自动化测试工具,支持驱动不同的浏览器,Firefox,IE,Chrome等,也包含HtmlUnit提供的驱动实现。
本文描述Selenium驱动Firefox,请求响应,设置cookies,驱动JS等方法,用他登录某主流weibo还是不错的。
二 版本
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.41.0</version> </dependency>
三 典型应用
1)打开Google,搜索baidu
可以看到Firefox从打开,填写表单,到提交打开新页面过程。
/**
* 打开google搜索百度
*
* @param queryStr
*/
public static void demo() {
String url = "http://www.google.com.hk";
WebDriver webDriver = new FirefoxDriver();
// 打开google
webDriver.get(url);
// 使用Selenium的dom模型获取form
WebElement webElement = webDriver.findElement(By.name("q"));
webElement.sendKeys("baidu");
webElement.submit();
// 通过判断 title 内容等待搜索页面加载完毕,Timeout 设置10秒
(new WebDriverWait(webDriver, 100)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().indexOf("baidu") != -1;
}
});
String responseBody = webDriver.getPageSource();
System.out.println("Response : " + responseBody);
// 关闭浏览器
webDriver.close();
}
2)获取动态网页
与下面的请求响应一样,打开页面等待加载完毕即可,JS填充页面,AJAX都OK。
四 样例
(1)请求响应
public static void main(String[] args) throws Exception {
String url = "http://www.google.com";
WebDriver webDriver = new FirefoxDriver();
// 打开google
webDriver.get(url);
String responseBody = webDriver.getPageSource();
System.out.println("Response : " + responseBody);
webDriver.quit();
}
(2)配置不加载资源
/**
* 获得不加载 css,图片,flash的浏览器
* @return
*/
public WebDriver getNoResouceWebDriver(){
FirefoxProfile firefoxProfile = new FirefoxProfile();
// 去掉css
firefoxProfile.setPreference("permissions.default.stylesheet", 2);
// 去掉图片
firefoxProfile.setPreference("permissions.default.image", 2);
// 去掉flash
firefoxProfile.setPreference("dom.ipc.plugins.enabled.libflashplayer.so", false);
return new FirefoxDriver(firefoxProfile);
}
(3)配置Firefox路径
启动报找不到Firefox的时候可以使用:System.setProperty("webdriver.firefox.bin", firefoxPath)
(4)Cookies
1)设置Cookies
public void setCookies(WebDriver,webDriver,Map<String, String> cookies) {
if (cookies != null && cookies.size() > 0) {
for (Entry<String, String> c : cookies.entrySet()) {
Cookie cookie = new Cookie(c.getKey(), c.getValue());
webDriver.manage().addCookie(cookie);
System.out.println("Set Cookies : " + c.getKey() + " | " + c.getValue());
}
}
}
2)获取响应Cookies
public Map<String,String> getCookies(WebDriver webDriver){
Set<Cookie> cookies = webDriver.manage().getCookies();
Map<String, String> responseCookies = new HashMap<String,String>();
for (Cookie c : cookies) {
responseCookies.put(c.getName(), c.getValue());
}
return responseCookies;
}
3)清理Cookies
/**
* 清除所有cookie
*/
public void clearCookies(WebDriver webDriver) {
webDriver.manage().deleteAllCookies();
}
(5)驱动JS
Selenium 的Dom对不可见的Element(html有但是CSS属性为不显示等)找不到,这时候使用JS操作和提交是个不错的选择:
public void doWeb(WebDriver webDriver) {
StringBuilder js = new StringBuilder();
js.append("document.getElementsByName('username')[1].value='").append(WeiboAccount.USERNAME)
.append("';");
js.append("document.getElementsByName('password')[1].value='").append(WeiboAccount.PASSWORD)
.append("';");
js.append("document.getElementsByClassName('W_btn_g')[1].click();");
((JavascriptExecutor) webDriver).executeScript(js.toString());
(new WebDriverWait(webDriver, 100)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().indexOf("我的首页") != -1;
}
});
}