原文地址是,http://xiaorui.cc
phantomjs无意是强大的无界面的webkit浏览器工具,但是对于有些网站来说,他的返回过慢了点。
我这边是在服务端控制超时的时间,gevent subprocess的组合,但是因为subprocess和我的另一组逻辑有些冲突,所以把超时的逻辑改到了 js 文件里面。
var system = require('system');
var args = system.args;
var url = args[1];
var page = require('webpage').create();
page.settings.resourceTimeout = 5000; // 5 seconds
page.onResourceTimeout = function(e) {
console.log(e.errorCode); // it'll probably be 408
console.log(e.errorString); // it'll probably be 'Network timeout on resource'
console.log(e.url); // the url whose request timed out
phantom.exit(1);
};
page.open(url, function(status) {
if (status === 'success') {
var html = page.evaluate(function() {
return document.documentElement.outerHTML;
});
console.log(html);
}
phantom.exit();
});
//$phantomjs xx.js http://bbs.pcbaby.com.cn/topic-2149414.html
另外提下,phantomjs 可以预先加cookie的。
var webPage = require('webpage');
var page = webPage.create();
phantom.addCookie({
'name' : 'Valid-Cookie-Name', /* required property */
'value' : 'Valid-Cookie-Value', /* required property */
'domain' : 'localhost',
'path' : '/foo', /* required property */
'httponly' : true,
'secure' : false,
'expires' : (new Date()).getTime() + (1000 * 60 * 60) /* <-- expires in 1 hour */
});
