我通过casperjs使用phantomjs成功抓取多个网站的截图。我通过获取一个网站http://fiver.com来解决此元素中的背景横幅问题,但我遇到了实际问题:
<div class="hero-slide sel" style="background-image: url('//cdnil21.fiverrcdn.com/assets/v2_photos/sellerpage-coverphoto-779e2108b002090406e707086772ad9b.jpg');">
<img alt="Sellerpage coverphoto" src="//cdnil21.fiverrcdn.com/assets/v2_photos/sellerpage-coverphoto-779e2108b002090406e707086772ad9b.jpg">
</div>
然后<div class="packages-list cf">
中的前三张图片也不会呈现。那些图像跟随那些渲染到png就好了。
正在使用的版本:
我使用了casperjs的以下页面设置:
pageSettings: {
javascriptEnabled: true,
loadImages: true,
loadPlugins: true,
localToRemoteUrlAccessEnabled: true,
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
} });
我正在加载页面,该页面已成功重定向到https网址。我正在运行此配置文件:
{"sslProtocol": "any",
"ignoreSslErrors": true,
"ssl-certificates-path": "ssl",
"web-security": false,
"cookiesFile": "biscuit",
"maxDiskCacheSize": 1000, "diskCache": true }
执行并等待加载所有内容的代码是:
this.thenOpen(screenshotUrl, function() {
this.wait(25000);
// Fix transparent background rendering bug
// Courtesy of: http://uggedal.com/journal/phantomjs-default-background-color/
this.evaluate(function() {
// css injection to force backgrounds to print
var style = document.createElement('style'),
text = document.createTextNode('body { background: #fff; -webkit-print-color-adjust: exact; }');
style.setAttribute('type', 'text/css');
style.appendChild(text);
document.head.insertBefore(style, document.head.firstChild);
var images = document.getElementsByTagName('img');
images = Array.prototype.filter.call(images, function(i) { return !i.complete; });
window.imagesNotLoaded = images.length;
Array.prototype.forEach.call(images, function(i) {
i.onload = function() { window.imagesNotLoaded--; };
});
});
});
casper.waitFor(function() {
return this.evaluate(function() {
return window.imagesNotLoaded == 0;
});
});
this.then(function(){
this.echo('Screenshot for ' + viewport.name + ' (' + viewport.viewport.width + 'x' + viewport.viewport.height + ')', 'info');
this.capture('screenshots/' + screenshotDateTime + '/' + viewport.name + '-' + viewport.viewport.width + 'x' + viewport.viewport.height + '.png', {
top: 0,
left: 0,
width: viewport.viewport.width,
height: viewport.viewport.height
});
});
我已经尝试将等待设置为高达100000,但它仍然无法正常工作。在评估中我注入了一些css并运行了一个试图等待所有图像加载的函数。我进入我的this.then函数将图像渲染到磁盘。
我用这个把头发拉了出来。屏幕截图为http://postimg.org/image/flvpvhy6v/
有什么想法吗?
答案 0 :(得分:2)
JavaScript没有阻塞等待或休眠功能。因此,当您wait
时,您将安排异步步骤。 evaluate
电话后,您的代码包含wait
来电。 evaluate
调用是同步/阻止,但wait
不是,因此wait
将在evaluate
之后执行。您必须将同步代码放在诸如wait*
或then*
之类的步进函数的回调中。
this.wait(25000, function(){
this.evaluate(function() {
// some code
});
});