首页 > IT职业 > IT图书 > PhantomJS如何在python爬虫中测试页面?
开网页加载一直停滞不前,让人比较烦躁。不能关掉它,重新开启似乎又是老样子。在等待的途中我们不如做一些有意思的事情,不至于让时间白白的浪费掉。PhantomJS不仅可以获取网页数据,还可以用来测试页面加载的速度,是不是很神奇?一想到要摆脱慢慢打开网页的烦恼,睡觉都要笑出声了。接下来我们就开始今天的学习吧。
下面这个例子计算了一个页面的加载速度,同时还用到了命令行传参的特性。新建文件保存为 loadspeed.js
var page = require('webpage').create(),
system = require('system'),
t, address;
var page = require('webpage').create(),
system = require('system'),
t, address;
if (system.args.length === 1) {
console.log('Usage: loadspeed.js <some URL>');
phantom.exit();
}
t = Date.now();
address = system.args[1];
page.open(address, function(status) {
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
t = Date.now() - t;
console.log('Loading ' + system.args[1]);
console.log('Loading time ' + t + ' msec');
}
phantom.exit();
});
程序判断了参数的多少,如果参数不够,那么终止运行。然后记录了打开页面的时间,请求页面之后,再纪录当前时间,二者之差就是页面加载速度。
phantomjs loadspeed.js http://cuiqingcai.com
运行结果
Loading http://cuiqingcai.com Loading time 11678 msec
这个时间包括 JS 渲染的时间,当然和网速也有关。
以上就是python爬虫中PhantomJS测试页面加载速度的方法。在网页加载速度方面,小编是不能让大家被这种问题困住的。把更多的时间解放出来,多学点其他知识吧。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3643/viewspace-2832289/ ,如需转载,请注明出处,否则将追究法律责任。