抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

Mr.wang

Time flies and people come and go

讲述搭建博客的一切

无头浏览器 文档

你在谷歌浏览器所得到的,在这也能得到

  1. 生成页面 PDF
  2. 抓取 SPA(单页应用)并生成预渲染内容(即“SSR”(服务器端渲染))
  3. 自动提交表单,进行 UI 测试,键盘输入等。
  4. 爬虫

安装

1
2
3
4
mkdir test
npm init
npm install puppeteer
touch test.js

test.js部分示例
执行环境 node
执行命令 node test.js

生成页面 PDF

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', {waitUntil: 'networkidle2'});
await page.pdf({path: 'baidu.pdf', format: 'A4'});

await browser.close();
})();

截图

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'});

await browser.close();
})();

自动提交表单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 在无头浏览器自动填写表单并提交
*/
const puppeteer = require("puppeteer");

const autoSubmitForm = async (url, path) => {
// 启动浏览器
const browser = await puppeteer.launch({
// 关闭无头模式,方便我们看到这个无头浏览器执行的过程
headless: false
});
// 打开页面
const page = await browser.newPage();
// 设置浏览器视窗
page.setViewport({
width: 1376,
height: 768
});
// 地址栏输入网页地址
await page.goto(url);
// await page.type("#kw", "网抑云", {
// delay: 1000 // 控制 keypress 也就是每个字母输入的间隔
// });
await page.focus("#kw");
await page.keyboard.type("网抑云", {
delay: 1000 // 控制 keypress 也就是每个字母输入的间隔
});
await page.keyboard.press("Enter");
// await page.press("Enter");
// 不关闭浏览器,看看效果
// await browser.close();
};
module.exports = autoSubmitForm;

if (require.main === module) {
// for test
autoSubmitForm("http://www.baidu.com");
}

评论