14
使用 Puppeteer 在 Node 环境生成 HTML 截图
source link: https://www.itwork.club/2020/09/09/generate-html-screenshot-by-puppeteer/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Sep 09, 2020NodeJS39点击
Puppeteer 是 Chrome
团队维护的一个无界面 Chrome
工具,我们可以利用它在 NodJS
环境生成网页截图
创建测试目录
1
2
3
4
mkdir node_images
cd node_images
touch index.js
npm init
通过 npm
或者 yarn
在项目内安装 puppeteer
1
2
npm i puppeteer
# or "yarn add puppeteer"
生成网页截图
1
2
3
4
5
6
7
8
9
10
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.baidu.com');
await page.screenshot({path: 'baidu.png'}); // path 指定了图片保存路径
await browser.close();
})();
执行上述代码 node index.js
, 会在当前目录下生成名为 baidu.png
的图片
通过 setViewport
方法可以对视窗
进行配置
1
2
3
4
5
await page.setViewport({
width: 345,
height: 345,
deviceScaleFactor: 2
});
页面内容也可以是 HTML 字符串
1
await page.setContent('<html><div> ABC </div></html>')
如果想得到截图内容(如 base64)
而不是保存图片到目录中,可以通过 screenshort
方法的返回值得到
1
2
3
4
const result = await page.screenshot({
encoding: "base64"
});
console.log(result)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK