您的位置:首页 > Web前端 > JavaScript

使用phantomjs抓取JS动态生成的页面

2016-10-18 10:52 651 查看
关于phantomjs

phantomjs实现了一个无界面的webkit浏览器。虽然没有界面,但dom渲染、js运行、网络访问等API都很完整。可以利用phantomjs来下载js生成的页面。

下载phantomjs(http://phantomjs.org/download.html)。解压到任意目录,在Windows下将包含phantomjs.exe的目录添加到系统路径。Linux下 phantomjs2.0还没有提供下载的包,需要手动编译。centos 安装phantomjs步骤如下:

在CentOS 6上测试可行。

安装依赖环境:

sudo yum -y install gcc gcc-c++ make flex bison gperf ruby \
openssl-devel freetype-devel fontconfig-devel libicu-devel sqlite-devel \
libpng-devel libjpeg-devel


下载进行编译:

git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 2.0
./build.sh


使用示例

示例一

由于PhantomJS 是一个基于 WebKit 的服务器端 JavaScript API,若要直接使用则需要js脚本进行调用。

使用phantomjs去获取页面,然后用Java调用phantomjs来获取内容。

codes.js 代码:

system = require('system')
address = system.args[1];//获得命令行第二个参数 接下来会用到
//console.log('Loading a web page');
var page = require('webpage').create();
var url = address;
//console.log(url);
page.open(url, function (status) {
//Page is loaded!
if (status !== 'success') {
console.log('Unable to post!');
} else {
//console.log(page.content);
//var title = page.evaluate(function() {
//  return document.title;//示范下如何使用页面的jsapi去操作页面的  www.oicqzone.com
//  });
//console.log(title);

console.log(page.content);
}
phantom.exit();
});


Java调用代码:

public static void getContent(String url) throws IOException {
Runtime rt = Runtime.getRuntime();
//这里的codes.js是保存在D盘下面的phantomjs目录中
Process p = rt.exec("D:/phantomjs-2.0.0-windows/bin/phantomjs.exe D:/phantomjs/codes.js "+url);
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sbf = new StringBuffer();
String tmp = "";
while((tmp = br.readLine())!=null){
sbf.append(tmp);
}
System.out.println(sbf.toString());
}


示例二

上一博文中介绍了selenium。现在有了phantomjs,就可以使用selenium来运行ghostdriver了。思路和运行chromedriver一样,只是ghostdriver可以驱动phantomjs。现在ghostdriver Java包已经和phantomjs绑定一起了,只要安装ghostdriver就可以使用了。如下添加maven依赖

<dependency>
<groupId>com.github.detro</groupId>
<artifactId>phantomjsdriver</artifactId>
<version>1.2.0</version>
</dependency>


使用的方法和selenium的其它驱动类似。因为是驱动第三方进程进行解析,而创建进程的开销还是比较大的,所以应尽量对webDriver进行复用会比较好。

一些问题

再启动应用的时候,有些机器中出现如下的异常信息,

org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:65377/status] to be available after 20000 ms


可能是tcp端口遭到占用,或者是driver版本和phantomjs版本不兼容所致。经过测试,有些机器中ghostdriver目前的版本驱动不了phantomjs2.0,把phantomjs降低一个版本就好使了。如phantomjs1.9.8。

参考:http://blog.csdn.net/tengdazhang770960436/article/details/41348035

PhantomJSDriver文档:https://cdn.rawgit.com/detro/ghostdriver/master/binding/java/docs/javadoc/index.html

原文参考:http://blog.csdn.net/lgcssx/article/details/48092007
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  webkit windows api 浏览器