phantomjs官网是这么说的,‘整站测试,屏幕捕获,自动翻页,网络监控’,目前比较流行用来爬取复杂的,难以经过api或正则匹配的页面,好比页面是经过异步加载。phantomjs就是一个完整的浏览器只能没有界面,所以咱们能够用它来模拟真正的浏览器去访问页面,而后再获取页面。我要说的重点是如何在node中调用phantomjs来获取页面。node
GitHub地址:https://github.com/amir20/phantomjs-nodegit
这里只作简单说明详细api见github。github
1.安装web
npm install phantomnpm
2.模块封装(如下代码基于es7,需支持async/await,node版本>7.0),更详细使用可查看phantomjs官方文档api
1 'use strict' 2 3 const phantom = require('phantom'); 4 5 let getPic = async ( name ) => { 6 //url路径 7 let url = 'http:///'+name; 8 //建立一个实例 9 const instance = await phantom.create(); 10 //建立一个页面 11 const page = await instance.createPage(); 12 //设置页面参数 13 await page.property( 'viewportSize' , { width : 1800 , height : 1200 } ); 14 //打开url,返回状态(url有转码,解决中文问题) 15 const status = await page.open( encodeURI( url ) ); 16 console.log( status ); 17 //延时等待页面js执行完成(phantomjs只是等待页面上所有资源加载完毕,不包含页面js执行时间,因此需延时一段时间等待js) 18 await lateTime( 500 ); 19 //输出页面到当前目录下 20 await page.render(`${ name }--${Date.now()}.png`); 21 //销毁实例 22 await instance.exit(); 23 //返回数据 24 return 'xxx'; 25 }; 26 27 let lateTime = ( time ) =>{ 28 return new Promise( function(resolve,reject){ 29 setTimeout(function(){ 30 resolve(); 31 }, time ); 32 } ); 33 } 34 //暴露接口 35 module.exports = getPic ;