Phantomjs - 获取网页的屏幕截图

时间:2013-06-19 11:15:36

标签: javascript jquery phantomjs frontend

我有一个网址(例如http://www.example.com/OtterBox-77-24444-Commuter-Series-Optimus/dp/B00A21KPEI/ref=pd_sim_cps_4),想要截取它并在我的网页上预览。意思是,用户点击预览按钮,PhantomJS需要以PNG / JPEG格式预览网页

我也可以使用任何其他开源。

2 个答案:

答案 0 :(得分:32)

我将假设您已经安装了Phantomjs并在.bashrc中创建了一个别名,或者更新了系统路径以调用Phantomjs二进制文件。如果没有,您需要仔细阅读一些初学者教程:http://net.tutsplus.com/tutorials/javascript-ajax/testing-javascript-with-phantomjs/

完成设置后,您需要编写一个简单的javascript文件,您将在终端(或shell,如果您使用的是Windows)中调用该文件。我将在下面提供一个简单的示例脚本。

var WebPage = require('webpage');
page = WebPage.create();
page.open('http://google.com');
page.onLoadFinished = function() {
   page.render('googleScreenShot' + '.png');
   phantom.exit();}

然后,保存您的js文件。打开终端或shell并运行以下

phantomjs yourFile.js

就是这样。检查你调用js文件的目录,你应该有一个png文件,其中包含你网页的屏幕截图。

这很简单,并且有很多关于使用phantomjs的注意事项,但这与我能做到的基本相同。如果您需要phantomjs的其他配方,请尝试查看以下示例脚本:https://github.com/ariya/phantomjs/wiki/Examples

答案 1 :(得分:12)

上述答案适用于基本用法,但PhantomJS不知道是否已加载所有AJAX请求。我让url-to-image来帮助解决这个问题。

  1. npm install url-to-image
  2. 编写screenshot.js

    var screenshot = require('url-to-image');
    screenshot('http://google.com', 'google.png').done(function() {
        console.log('http://google.com screenshot saved to google.png');
    });
    
  3. 运行脚本node screenshot.js
相关问题