PhantomJS捕获移动浏览器截图

5
我正在尝试使用PhantomJS创建网页截图,但是我得到的是移动浏览器的图片。我正在使用MAC OS Yosemite操作系统。以下是我的JavaScript代码:

screen.js

var WebPage = require('webpage');
page = WebPage.create();
page.open('http://www.apple.com');
page.onLoadFinished = function() {
    window.setTimeout(function () {
        page.render('appleScreenShot' + '.png');
        phantom.exit();
    }, 2000);
}

以下是我的命令行代码

phantomjs --ignore-ssl-errors=true --web-security=false --ssl-protocol=tlsv1 --debug=true screen.js
4个回答

7
你可能会发现需要针对某些网站指定 viewportSize (甚至是zoomFactor),具体取决于它们资源中所指定的媒体查询。

从关于viewportSize的文档中可以了解到:

因为PhantomJS是无头浏览器(不会显示任何内容),所以viewportSize有效地模拟了传统浏览器中窗口的大小。

使用示例:

page.viewportSize = {
    width: 1280,
    height: 800
};
page.zoomFactor = 1; //default value is 1

谢谢Dan。设置page.viewportSize对我很有帮助。我使用了最大分辨率。page.viewportSize = { width: 1600, height: 1200 }; - Deepak
请问您能否将那个问题标记为正确答案。 - Adi Prasetyo

1

我建议您添加背景颜色渲染,因为默认情况下将是透明背景。

page.evaluate(function() {
    document.body.bgColor = 'white';
});

example


0

你可以在Node中使用NightmareJs:

const Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false })
nightmare
  .useragent('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')
  .viewport(1200, 1800)
  .wait()
  .goto('url...')
  .wait()
  .screenshot('image.png')
  .end()
  .then(function (result) {
    console.log('page done');
 })
  .catch(function (error) {
    console.error('Error:', error);
 })

我发现对于截图来说,它比PhantomJs更容易使用


-1

在Java中,我可以更改用户代理字符串。这对我很有效。

DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setJavascriptEnabled(true);
        String userAgent = "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1";
 capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX + "userAgent", userAgent);
            driver = new PhantomJSDriver(capabilities);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接