puppeteer去掉同源策略及请求拦截
- 2020 年 8 月 19 日
- 筆記
puppeteer是一个功能强大的工具,在自动化测试和爬虫方面应用广泛,这里谈一下如何在puppeteer中关掉同源策略和进行请求拦截。
同源策略
同源策略为web 安全提供了有力的保障,但是有时候我们需要在localhost的情况下访问服务器的api,这时就需要去掉同源策略的限制,让http畅通无阻。
chrome的启动是支持很多参数的,其中一个就是来禁用同源策略的。当我们在chrome启动时加入--disable-web-security
这个参数时,chrome的同源策略就会被关闭。对于关闭puppetter的同源策略就更简单了,只要在launch方法中加入这个参数就可以了:
const browser = await puppeteer.launch({
headless: false,
devtools: true,
defaultViewport: {
width: 1280,
height: 720,
},
args: [
'--disable-web-security'
],
});
更多有用的参数可以参考这里.
然后接下来谈谈拦截请求
page.setRequestInterception
可以拦截请求的就是这个方法了。我们来看官方给出的一段代码:
const puppeteer = require('puppeteer');
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg'))
interceptedRequest.abort();
else
interceptedRequest.continue();
});
await page.goto('//example.com');
await browser.close();
});
这里,我们首先开启了拦截请求,然后对url以jpg或者png结尾的,调用abort(),使这个请求失败,其他的则继续发到服务器。当然,如果只是这么简单的话,是说明不了这个方法的强大之处的,因为我们还可以直接返回一个响应。举个例子:
await page.setRequestInterception(true);
page.on('request', request => {
request.respond({
status: 404,
contentType: 'text/plain',
body: 'Not Found!'
});
});
对方不想说话,并丢过来一个404。当然,除了404,其他的200,301,500也都是可以的。
还可以在请求过程中”添油加醋”:
request.url() // 读取url
request.headers() // 读取headers
request.postData() // 读取postData
request.method() // 读取postData
request.continue({
url: '',
method: '',
postData: {},
headers: {}
})
你可以在请求过程中替换一些请求的参数,比如把url中的baidu替换成google,改掉postData或者headers里的一些信息,emmm,我忽然有了一个大胆的想法(完)。
参考:
//pptr.dev/#?product=Puppeteer&version=v5.2.1&show=api-pageevaluatehandlepagefunction-args
//zhaoqize.github.io/puppeteer-api-zh_CN/#?product=Puppeteer&version=v5.2.1&show=api-requestcontinueoverrides