Puppeteer 是 Chrome 开发团队在 2017 年发布的一个 Node.js 包,用来模拟 Chrome 浏览器的运行。
demo只支持将简单不需要翻页,不需要登陆的页面转换为图片
需要node环境,以及npm或cnpm包管理工具(自行百度)
开始
进入一个新的项目目录,命令模式进入项目目录
npm init
然后一直回车,内容可不填。
修改 package.json 文件为下面的内容:
//package.json
{
"name": "html_to_png",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"puppeteer": "^2.1.1"
}
}
安装依赖
npm install
在项目根目录下创建index.js文件
// index.js
// 引入puppeteer
const puppeteer = require('puppeteer');
// 需要生成的图的文件名
const fileName = 'example.png';
// html网络地址
const url = 'https://www.jianshu.com/p/5abd81129f8c';
(async () => {
const browser = await puppeteer.launch({
defaultViewport: {
width: 1600,
height: 937
},
});
const page = await browser.newPage();
await page.goto(url);
await page.screenshot({ path: fileName, fullPage: true });
await browser.close();
})();
运行
npm run start
等待几秒后,如果在项目目录下生成图片,说明成功了。