puppeteer是一个基于cdp协议的功能强大的工具,在自动化测试和爬虫方面应用普遍,这里谈一下如何在puppeteer中关掉同源策略和进行请求拦截。html
同源策略为web 安全提供了有力的保障,可是有时候咱们须要在localhost的状况下访问服务器的api,这时就须要去掉同源策略的限制,让http畅通无阻。git
chrome的启动是支持不少参数的,其中一个就是来禁用同源策略的。当咱们在chrome启动时加入--disable-web-security
这个参数时,chrome的同源策略就会被关闭。对于关闭puppetter的同源策略就更简单了,只要在launch方法中加入这个参数就能够了:github
const browser = await puppeteer.launch({ headless: false, devtools: true, defaultViewport: { width: 1280, height: 720, }, args: [ '--disable-web-security' ], });
更多有用的参数能够参考这里.web
而后接下来谈谈拦截请求chrome
能够拦截请求的就是这个方法了。咱们来看官方给出的一段代码:api
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('https://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也都是能够的。服务器
还能够在请求过程当中''添油加醋'':less
request.url() // 读取url request.headers() // 读取headers request.postData() // 读取postData request.method() // 读取postData request.continue({ url: '', method: '', postData: {}, headers: {} })
你能够在请求过程当中替换一些请求的参数,好比把url中的baidu替换成google,改掉postData或者headers里的一些信息,emmm,我突然有了一个大胆的想法(完)。async
参考:
https://pptr.dev/#?product=Puppeteer&version=v5.2.1&show=api-pageevaluatehandlepagefunction-args
https://zhaoqize.github.io/puppeteer-api-zh_CN/#?product=Puppeteer&version=v5.2.1&show=api-requestcontinueoverrides