puppeteer去掉同源策略及請求攔截

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

page.setRequestInterception

能夠攔截請求的就是這個方法了。咱們來看官方給出的一段代碼: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