如何从shell获取网页的一部分快照?

yll*_*ate 5 javascript bash imagemagick phantomjs

我有一个网页的一部分,我需要在给定的时间间隔拍摄一个gif快照.快照需要是整页大小分辨率,但正如我所说,它只会到达页面上的某个位置(在这种情况下它位于表格之后).

获取像这样的页面快照图像图像的最佳方法是什么?我想把它扔进一个cron工作并忘掉它,但我并不是很容易看到一个可以快速完成这项任务的工具.

解:

根据@ Eduardo的出色方向,我实现了一个基于phantomjs和imagemagick的干净快速的解决方案(Mac:brew install phantomjs&brew install imagemagick):

*注意:如果你想完全删除imagemagick,只需将以下内容添加到rasterize.js: page.clipRect = { top: 10, left: 10, width: 500, height: 500 }

#! /usr/bin/env bash
# Used with PhantomJS - rasterize.js source: http://j.mp/xC7u1Z

refresh_seconds=30

while true; do
    date_now=`date +"%Y-%m-%d %H%M"` 

    phantomjs rasterize.js $1 "${date_now}-original.png"  # just sucking in the first arg from shell for the URL
    convert "${date_now}-original.png" -crop 500x610+8+16 "${date_now}.png" # crop args: WIDTHxHEIGHT+LEFT_MARGIN+TOP_MARGIN
    rm "${date_now}-original.png"

    echo "Got image: ${date_now}.png - Now waiting ${refresh_seconds} seconds for next image..."
    sleep ${refresh_seconds}
done
Run Code Online (Sandbox Code Playgroud)

这里是phantomjs在上面使用的js:

// As explained here: http://code.google.com/p/phantomjs/wiki/QuickStart

var page = new WebPage(),
    address, output, size;

if (phantom.args.length < 2 || phantom.args.length > 3) {
    console.log('Usage: rasterize.js URL filename');
    phantom.exit();
} else {
    address = phantom.args[0];
    output = phantom.args[1];
    page.viewportSize = { width: 600, height: 600 };
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
        } else {
            window.setTimeout(function () {
                page.render(output);
                phantom.exit();
            }, 200);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Edu*_*rdo 4

这个问题已经在这里得到解答: How can I take a Screenshot/image of a website using Python?

它已于 09 年得到答复,但该选项仍然非常有效。我将尝试扩展更多选项。

这些工具将为您提供整页快照,稍后您可以使用 imagemagick 轻松剪辑。

现在您可能拥有的另一个选择是Phantomjs。Phantom 是一款在 Node 上运行的无头浏览器,它允许您拍摄整个页面或页面的某个区域的图片。

看一下这个例子

var page = new WebPage(),
    address, output, size;

if (phantom.args.length < 2 || phantom.args.length > 3) {
    console.log('Usage: rasterize.js URL filename');
    phantom.exit();
} else {
    address = phantom.args[0];
    output = phantom.args[1];
    page.viewportSize = { width: 600, height: 600 };
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
        } else {
            window.setTimeout(function () {
                page.render(output);
                phantom.exit();
            }, 200);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)