---
title: "Phantomjs/Casperjs, HtmlUnit, Selenium在获取Javascript页面时特性对比"
author: "Ihavegotyou"
date: "2015-11-28T13:53:58Z"
tags: []
categories: ["开源软件"]
slug: "phantomjs-casperjs-htmlunit-selenium-javascript"
draft: false
lastmod: "2015-11-28T14:06:54Z"
id: 2259941
url: "https://ucstudio.iteye.com/blog/2259941"
---

**Phantomjs/Casperjs, HtmlUnit, Selenium在获取Javascript页面时特性对比**

基于Phantomjs 2.0.0/Casperjs 1.1.0-beta3, Htmlunit 2.18, Selenium 2.47.1,在获取Javascript 页面时,对JavaScript engine,session/cookie支持, request url追踪, browser支持,以及访问速度,稳定性等方面进行对比如下：

 

 

框架/程序

对比项目

JavaScript engine

Cookie

request 

\[received] 

url

Browser

访问速度,稳定性,可扩展性等

[Phantomjs](http://phantomjs.org/)/[Casperjs](http://casperjs.org/)

Base on WebKit

支持

支持

Base on 

WebKit

访问速度较快，有时程序会crash,支持各种js 框架，

缺点:支持的js有限

[HtmlUnit](http://htmlunit.sourceforge.net/)

Rhino

支持

支持

Firefox or Internet Explorer

访问速度最快,比较稳定,支持各种js 框架,可以由页面类容模拟url请求. 缺点:支持的js有限

[Selenium](http://docs.seleniumhq.org/download/)

Most engine

支持

不支持

Most Browsers

访问速度太慢，速度也不稳定，而且带有UI,想跨平台必须使用RemoteWebDriver,优点: 支持大部分浏览器

 

 

 

 

\`

 

 示例代码:

[Phantomjs](http://phantomjs.org/)/[Casperjs](http://casperjs.org/)：

-Cookie:

 

 

```
var fs = require('fs');
if(fs.isFile(cookieFile)) {
        phantom.cookies = JSON.parse(fs.read(cookieFile));
}

var cookies = JSON.stringify(phantom.cookies);
fs.write(cookieFile, cookies, 644);
```

 

-request \[received] url:

 

 

```
casper.on("resource.requested", function(resource){
｝）;
```

 

 

[HtmlUnit](http://htmlunit.sourceforge.net/)：

-Cookie:

 

 

```
webClient.getCookieManager().addCookie(cookie);
webClient.getCookieManager().getCookies();
webClient.getCookieManager().clearCookies();
```

 

 

-request \[received] url:

 

```
public static class InterceptWebConnection extends FalsifyingWebConnection{
｝
```

 

[Selenium](http://docs.seleniumhq.org/download/)：

-Cookie:

 

```
WebDriver driver = ...;
for (Cookie ck : driver.manage().getCookies()) {
		       
		        	javax.servlet.http.Cookie generateCookie = new javax.servlet.http.Cookie(ck.getName(), ck.getValue());
		        	generateCookie.setMaxAge(3600); 
		        	response.addCookie(generateCookie);
	            }
```