Phantomjs:截图当前页面


Phantomjs: take screenshot of the current page?

我正在尝试使用Phantomjs从用户所在的同一页面捕获屏幕截图。

例如,一个用户在mypage.html上,并对该页面的元素进行了一些更改,现在我需要截图该页面(mypage.html)内的元素(DIV)并保存它。

我发现了一些Phantomjs and php的例子,我在服务器上测试和工作过,它也将图像存储在我的服务器上,但我发现的所有例子都是用于截屏外部页面/URL,而不是"当前页面"。

这在Html2canvas中是一个相当直接的过程,但生成的图像质量一点也不好,所以我决定使用Phantomjs来生成更高质量的屏幕截图,而且它还允许我放大页面。

下面是一个使用Phantomjs截屏外部URL的简单示例:

var system = require("system");
if (system.args.length > 0) {
    var page = require('webpage').create();
    page.open(system.args[1], function() {
        //viewportSize being the actual size of the headless browser
page.viewportSize = { width: 3000, height: 3000 };
//the clipRect is the portion of the page you are taking a screenshot of
page.clipRect = { top: 0, left: 0, width: 3000, height: 3000 };
page.zoomFactor = 300.0/72.0;
        var pageTitle = system.args[1].replace(/http.*'/'//g, "").replace("www.", "").split("/")[0]
        var filePath = "img/" + pageTitle + '.png';
        page.render(filePath);
        console.log(filePath);
        phantom.exit();
    });
}

有人能告诉我这是否可能吗?

EDIT(回答我自己的问题),

事实证明,如果用户在实时的基础上编辑了当前页面的元素,则无法对该页面进行屏幕截图。您可以使用phantomjs拍摄的唯一屏幕截图是页面的一个骨架。

原因:phantomjs是一个无头浏览器,使用在服务器上运行的QtWebKit,它不是一个与html2canvas相同的javascript库。

其他人在这里解释和体验:

对于我正在处理的项目来说,另一个问题是您需要拖放。无头驱动程序有一些基本功能,但如果你需要能够设置精确的坐标,你就只能使用Selenium了。

要拍摄当前页面的屏幕截图,必须将正确的URL传递给Phantom脚本

语法:

phantomjs <"Phantom code url(as in documentation report.js)"> <"page url of which you want to take scrrenshot"> <"result saving url">

现在假设您正在传递正确的URL:

  1. 在我的情况下,我无法截图我的页面,因为它有一个弹簧安全注释,所以它不允许我继续,所以请检查您添加到页面的任何安全性,如果是,请删除它,然后重试。

  2. 如果情况1不适用于你,那么你通过的URL肯定有问题,请仔细检查。

请让我知道,如果问题仍然存在,请张贴您得到的任何错误(如果发生)。