使用 PhantomJS-node 生成截图

在 Node Server 里截取网页生成图片

使用 phantomjs-node 可以方便的实现上面的功能

安装

1
$ npm install phantom --save

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const phantom = require('phantom');

(async function() {
const instance = await phantom.create();
const page = await instance.createPage();
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});

// 打开 https://stackoverflow.com/ 这个页面
const status = await page.open('https://stackoverflow.com/');

// 将页面里的 conent 打印出来
const content = await page.property('content');
console.log(content);

await instance.exit();
})();

上例就是 phantomjs-node 官方的示例

它把页面的内容打印了出来

如果我们想把页面内容以 pdf 或 png 的格式存下来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const phantom = require('phantom');

(async function() {
const instance = await phantom.create();
const page = await instance.createPage();

// 设置页面的大小
await page.property('viewportSize', { width: 1024, height: 600 });
const status = await page.open('https://stackoverflow.com/');
console.log(`Page opened with status [${status}].`);

// 以 pdf 格式将页面保存下来
await page.render('stackoverflow.pdf');
console.log(`File created at [./stackoverflow.pdf]`);

await instance.exit();
})();

在我的项目里,是将一个 HTML 字符串塞给了 phantom

出现一个问题:图片资源没有显示

查了相关 issuePR

最后,监听了 page 的 onLoadFinished 事件

1
2
3
4
5
page.on('onLoadFinished', async function(requestData) {

// 在 onLoadFinished 之后去获取图片
console.log('finished')
});

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2019/07/15/Use-PhantomJS-node/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

在 AMP 中获取动态数据