晋书云:“生犀不敢烧,燃之有异香,沾衣带,人能与鬼通”
之前几篇文章介绍了Selenium+Phantomjs用法,也探讨过性能优化问题。然而利用selenium或者说python去运行phantomjs本质上并不是高效的方法,再者selenium对于phantomjs的封装并不是特别完善(长久没有更新过),因此很有必要研究下原生态的phantomjs。于是我参考官网介绍,学习总结成文,在此记录分享。
phantomjs全面支持web而不需要浏览器,又称为无头浏览器,它是一个基于webkit的服务端javascript API,可以用于页面自动化,网络监测,网页截图,爬虫抓取等。phantomjs有很多api接口,接口语法用的就是js的语法,phantom提供了类,实例化以后可以调用对象的方法,通过回调函数可以实现自己想要的功能,其APi主要有web服务端Api、webPage APi、System APi等,这里主要介绍几种常用的api的用法。
phantomjs-Command Line Interface
描述:phantomjs命令行用法以及参数设置
首先我们看下如何调用phantomjs运行js脚本
可选参数:(只列举常用的)
- –disk-cache=[true|false] 缓存设置
- –ignore-ssl-errors=[true|false] 忽略ssl错误
- –load-images=[true|false] 加载图片
- –proxy=address:port 设置代理
有很多参数,不一一列举,详细参考:phantomjs-Command Line Interface
phantomjs-system module
描述:phantomjs系统操作APi
文档地址:phantomjs-system module
作用:用于system系统操作
args(获取程序输入参数)
代码(test.js)
运行:
phantomjs test.js hello
结果:
0 test.js
1 hello
功能:接受控制台输入参数。
env(系统环境变量)
代码(test.js):
运行:phantomjs test.js
功能:列出系统环境变量
os(平台类型)
代码(test.js):
运行:phantomjs test.js
结果:
32bit
windows
7
功能:输出运行平台类型
pid (进程id)
代码(test.js):
输出进程pid
platgform(平台信息)
代码(test.js):
运行结果:phantomjs
Phantomjs-web server module
描述:phantomjs web server module APi
文档地址:Phantomjs-web server module
作用:作为webserver服务端,提供http服务。
代码(test.js):
运行:phantomjs test.js
访问:http://localhost:8080
如果要指定ip与端口,则8080可以这样写:’127.0.0.1:9999’。
其中有2个参数,request与response。
request参数方法:
- request.method
- request.url
- request.httpVersion
- request.headers
- request.post
- request.postRaw
用来获取请求内容。
response参数方法:
- response.headers
- response.setheader(name,value)
- response.header(name)
- response.statusCode()
- response.setEncoding(“binary”)
- response.write(html_data)
- response.writeHead(statusCode,headers)
- reponse.close()
- reponse.closeGracefully()
Phantomjs-web page module
描述:phantomjs web page module APi
文档地址:Phantomjs-web page module
作用:用来发送http请求,获取网络资源,或者页面操作。
实例化api类
|
|
page方法
- page.content 源码
- page.title 标题
- page.cookie cookie
- page.plainText 网页内容(去除html)
- page.setting 参数设置
- page.url 当前url
clipRect剪切页面
|
|
content获取网页源码
|
|
cookie获取页面cookie
|
|
设置customHeaders内容:
|
|
plainText获取网页内容(去除html只留内容)
|
|
setting 请求头设置
|
|
zoomFactor缩略图创建
|
|
addcookie添加cookie
|
|
上传文件
|
|
render页面截图
|
|
更多例子请参考:examples
传送门
【phantomjs系列】phantomjs正确打开方式
【phantomjs系列】phantomjs api介绍
【phantomjs系列】selenium+phantomjs爬过的那些坑
【phantomjs系列】selenium+phantomjs性能优化