24

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

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

4

2 回答 2

34

我将假设你已经安装了 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

于 2013-06-19T16:59:01.283 回答
14

上面的答案对于基本用法很好,但 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
于 2014-03-06T22:57:00.737 回答