小编向大家介绍了phantomjs是什么(https://www.py.cn/web/js/22623.html),大家也应该知道了phantomjs可以用于网络爬虫,那么phantomjs爬虫到底是如何实现的呢?其实就是使用phantomjs操作网络爬虫,获取页面中使用js来下载和渲染信息,或者是获取链接处使用js来跳转后的真实地址。
一、phantomjs使用场景网络爬虫
获取页面中使用js来下载和渲染信息,或者是获取链接处使用js来跳转后的真实地址。
page.evaluate 方法提供了一个沙箱,操作和js中dom一样,可以简单的获取你想要的内容,避免了使用复杂的正则匹配内容。
二、phantomjs爬虫实现
1、新建一个Javascript文件
console.log('Hello, world!');
phantom.exit();2、在命令行输入:
phantomjs test.js
3、使用phantomjs操作网络爬虫
var page = require('webpage').create();
page.settings.resourceTimeout=5000;
page.onConsoleMessage = function (msg) {
console.log(msg);
}
phantom.outputEncoding = "gbk";
var url = "http://www.ifeng.com/";
page.open(url,function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
page.includeJs("http://libs.baidu.com/jquery/1.11.1/jquery.min.js",function () {
var result = page.evaluate(function(){
var result = $("#headLineDefault h1 a").html();
console.log("ifeng headline is : "+result);
return result;
})
console.log("result is :"+result);
})
}
setTimeout(function () {
phantom.exit();
},5000);
})以上就是phantomjs爬虫的介绍和使用实例,phantomjs爬虫很好用,但是速度有些慢,要耐心等待哦~



