**
Puppeteer常用命令
https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md //官方API列表
http://www.php.cn/js-tutorial-387019.html //puppeteer 破解滑动验证码
http://www.cnblogs.com/imgss/p/headless.html
http://cnodejs.org/topic/5a041412ad77fa2004549183
https://segmentfault.com/a/1190000011627343
1、
设置浏览器.
const browser = await puppeteer.launch({
// 若是手动下载的chromium需要指定chromium地址, 默认引用地址为 /项目目录/node_modules/puppeteer/.local-chromium/
executablePath: ‘/Applications/Chromium.app/Contents/MacOS/Chromium’,
timeout: 15000, //设置超时时间,
ignoreHTTPSErrors: true, // 如果是访问https页面 此属性会忽略https错误,
devtools: true, // 打开开发者工具, 当此值为true时, headless总为false,
headless: false, // 关闭headless模式, 不会打开浏览器,
})
2、
打开一个新标签页
const page = browser.newPage();
3、
页面跳转
await page.goto(‘https://cnodejs.com‘); //如果页面跳转其中一些资源加载超时会报错.
// 建议这样写可避免因为promise所报的超时错误.
await page.goto(‘https://cnodejs.com‘, {timeout: 3000}).then( () => {
console.log(‘跳转成功并且资源正确加载完毕.’);
}, () => {
console.log(‘跳转成功, 资源加载超时.’);
});
4、
设置浏览器参数,
const devices = require(‘puppeteer/DeviceDescriptors’);
// 设置测试机型.
const testDevice = devices[‘iPhone 6’];
await page.emulate(testDevice);
5、
page.url() 当前页面链接
获取页面标题
let title = await page.title();
6、
获取焦点
await page.focus(‘#elementId’);
7、
点击按钮
await page.click(‘#elementId’);
await page.tap(‘#elementId’); //用于手机端
8、
获取DOM
let el = await page.$(‘#elementId’); // 相当于document.querySelector(‘#elementId’);
await el.click(); // 执行点击事件
let list = await page.$$(‘.someclass’); // 相当于document.querySelectorAll(‘.someClass’);
获取DOM属性
let inputValue = await page.$eval(‘#input’, el => el.value); //如果是class不是id则只获取第一个标签内的内容
9、
文本输入
await page.type(‘#inputId’, ‘输入内容.’);
await page.type(‘#inputId’, ‘输入内容.’, { delay: 200 }); // 设置输入间隔200ms(拟人输入);
10、
evaluate
let result = await page.evaluate( () => {
// 获取一个元素, 这里可直接使用js
return document.getElementById(‘testEl’).getAttribute(‘anyAttr’);
})
console.log(result); // testEl的anyAttr属性值.
11、
waitFor 等待(元素或者函数或者一个延迟毫秒)
waitFor 详细文档
await page.waitFor(selectorOrFunctionOrTimeout[, options[, …args]]);
12、
设置页面样式
await page.mainFrame().addStyleTag({
content: ‘* { background-color: red; }’;
});
13、
屏幕截图
await page.screenshot({
path: ‘some/to/path.png’,
fullPage: true // 全屏截取, 默认false.
});
14、
保存网页为 pdf
打开一个网页,然后保存 pdf 到本地:
await page.pdf({
path: ‘path/to/saved.pdf’,
format: ‘A4’, // 保存尺寸
});
15、
发送请求. 在浏览器中使用fetch发送请求.
// 向http://example.com发送一个POST请求, 请求参数为 {a:1, b:2};
let result = await page.evaluete( async (options) => {
return await fetch(‘http://example.com‘, {
method: ‘POST’, //
header: {
‘Content-Type’: ‘application/json; charset=utf-8’
},
body: JSON.stringify(options)
})
.then(response => response.json())
.then(data => data)
.fail( e => console.log(‘Oops, error’, e));
}, { a: 1, b: 2});
console.log(result); //接口返回值.
16、
发送请求. 通过puppeteer的page.on(‘request’); 进行拦截. 使用goto进行触发请求.
await page.setRequestInterceptionEnabled(true);
page.on(‘request’, request => {
const overrides = {};
// 如果是需要请求的地址.
if (request.url === ‘http://www.google.com‘) {
//设置请求方式.
overrides.method = ‘POST’;
//设置参数
overrides.postData = ‘a=b&c=d’;
}
request.continue(overrides);
});
let response = await page.goto(‘http://www.google.com‘);
response.json();// 将response.body 转成json。
response.ok(); // 返回一个boolean值 如果状态码为200-299则为true, 其他则为false.
response.status; // 返回状态码
response.text(); // 返回 response body.
response.headers // 返回 HTTP headers
17、
关闭页面中的弹框
const puppeteer = require(‘puppeteer’);
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
// 当页面中有弹框调起的时候触发.
page.on(‘dialog’, async dialog => {
console.log(dialog.message()); //打印弹框的内容
await dialog.dismiss(); //关闭弹框
});
page.evaluate(() => alert(‘1’)); // 浏览器中执行 alert(‘1’);
});
18、自动提交表单
打开谷歌首页,输入关键字,回车进行搜索:
// 地址栏输入网页地址
await page.goto(‘https://google.com/‘, {
waitUntil: ‘networkidle’, // 等待网络状态为空闲的时候才继续执行
});
// 聚焦搜索框
// await page.click(‘#lst-ib’);
await page.focus(‘#lst-ib’);
// 输入搜索关键字
await page.type(‘辣子鸡’, {
delay: 1000, // 控制 keypress 也就是每个字母输入的间隔
});
// 回车
await page.press(‘Enter’);
19、
Page.
可以理解为我们常用的document.querySelector,而Page.
可
以
理
解
为
我
们
常
用
的
d
o
c
u
m
e
n
t
.
q
u
e
r
y
S
e
l
e
c
t
o
r
,
而
P
a
g
e
.
$ 则对应 document.querySelectorAll。