在Linux上利用phantomjs进行网页截图
1. phantomjs介绍
基于Javascript驱动的命令行webkit引擎,轻量级,安装简单,开发快速,渲染速度较快
无界面的webkit浏览器
更多介绍可以参考 http://code.google.com/p/phantomjs
2. phantomjs应用场景
web回归测试
网页截图,png,pdf
网络状况监控
3. phantom网页截图
以在ubuntu上截图为例。
1) Ubuntu 10.10上安装
| sudo add-apt-repository ppa:jerome-etienne/neoip sudo apt-get update sudo apt-get install phantomjs | 
2) 配置
目前,phantomjs还是需要x-server的依赖才可以运行的,因此需要安装xfvb(Xvfb is X virtual framebuffer, it acts like an in-memory X server (no output is produced to the screen).)
| sudo apt-get install xvfb | 
新建如下文件in /etc/init.d/Xvfb,内容如下:
| #! /bin/sh
 
### BEGIN INIT INFO
# Provides: Xvfb
# Required-Start: $local_fs $remote_fs
# Required-Stop:
# X-Start-Before:
# Default-Start: 2 3 4 5
# Default-Stop:
### END INIT INFO
 
N=/etc/init.d/Xvfb
 
set -e
 
case "$1" in
  start)
Xvfb :0 -screen 0 1024x768x24 &
;;
  stop|reload|restart|force-reload)
;;
  *)  
echo "Usage: $N {start|stop|restart|force-reload}" >&2exit 1
;;
esac
 
exit 0 | 
这里可以更近一步把xfvb设置开机启动项目:
| sudo apt-get install chkconfig chkconfig --add Xvfb | 
为了能够运行请在phantom执行前加入DISPLAY=:0参数:
| DISPLAY=:0 phantomjs <arguments> | 
3) 运行网页截图
新建一个js脚本,内容如下:
| var page = new WebPage(), address, output, size; if (phantom.args.length < 2 || phantom.args.length > 3) { console.log('Usage: rasterize.js URL filename'); phantom.exit(); } else { address = phantom.args[0]; output = phantom.args[1]; page.viewportSize = { width: 600, height: 600 }; page.open(address, function (status) { if (status !== 'success') { console.log('Unable to load the address!'); } else { window.setTimeout(function () { page.render(output); phantom.exit(); }, 200); } }); } | 
保存为snap.js
执行如下命令:
| phantomjs snap.js http://baidu.com baidu.com.png | 
即生成了截图文件baidu.com.png。
未完成话题,TBD的学习方向:
1)渲染网页结束后是否可以执行js
2)指定宽高截图
3)当屏数很多时候是否可以截断
 
	
				
Trackbacks.- 如何用phantomjs操作修改DOM并截图 | Neo 时刻准备着