之前在盘古的时候,每周值班的QA都要发送一个周版本测试报告邮件,长的大概是这个样子:
#-*- coding:utf-8 -*-
import sys
import os.path
from PyQt4 import QtGui,QtCore,QtWebKit
class PageShotter(QtGui.QWidget):
def __init__(self,url,parent=None):
QtGui.QWidget.__init__(self,parent)
self.url = url
def shot(self):
webView = QtWebKit.QWebView(self)
webView.load(QtCore.QUrl(self.url))
self.webPage = webView.page()
self.connect(webView,QtCore.SIGNAL("loadFinished(bool)"),self.savePage)
def savePage(self,finished):
if finished:
print u"开始截图!"
size = self.webPage.mainFrame().contentsSize()
print u"页面宽:%d,页面高:%d" % (size.width(),size.height())
self.webPage.setViewportSize(QtCore.QSize(size.width()+16,size.height()))
img = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
painter = QtGui.QPainter(img)
self.webPage.mainFrame().render(painter)
painter.end()
fileName= "shot.png";
if img.save(fileName):
filePath = os.path.join(os.path.dirname(__file__), fileName)
print u"截图完毕:%s" % filePath
else:
print u"截图失败";
else:
print u"网页加载失败!"
self.close()
if __name__=="__main__":
app = QtGui.QApplication(sys.argv)
shotter = PageShotter("http://crystalpot.cn/menu/0")
shotter.shot()
sys.exit(app.exec_())
代码很简单,开始用着也很舒爽,但是马上就遇到了一个问题,有时截图中某些图表还没有加载完毕。
var page = require('webpage').create(), address, output, size;
system = require('system');
if (system.args.length != 3) {
// 不带参数,即输入 phantomjs resize_webshot.js
console.log('less');
address = 'http://www.xxx.com';
output = 'example.png';
} else {
console.log('more');
address = system.args[1]; // 需要截图的url
output = system.args[2]; // 截图保存路径
}
page.viewportSize = { width: 1680, height: 1050 }; //解析分辨率建议设的大一点
page.open(address, function (status) {
//通过在页面上执行脚本获取页面的渲染高度
var bb = page.evaluate(function () {
return document.getElementsByTagName('html')[0].getBoundingClientRect();
});
// 按照实际页面的高度,设定渲染的宽高;这里的数值需要仔细调整
page.clipRect = {
top: bb.top+1,
left: bb.left+425,
width: bb.width-850,
height: bb.height-60
};
//预留一定的渲染时间
window.setTimeout(function() {
page.render(output);
page.close();
console.log('render ok');
var fs = require('fs');
var ss = output.split('/');
var pic = ss[ss.length-1];
var k = output.lastIndexOf('/');
var prefix = './';
if (k != -1){
prefix = output.substring(0, k+1);
}
//在截图完成后创建一个标志文件;无bug时可以删掉这两行
var file = fs.open(prefix+ 'done_'+ pic, 'w');
file.close();
phantom.exit();
}, 1000);
});