puppeteer stop redirect 的正确姿势及 net::ERR_FAILED 的解决
生活随笔
收集整理的這篇文章主要介紹了
puppeteer stop redirect 的正确姿势及 net::ERR_FAILED 的解决
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在官方文檔(puppeteer/api.md at master · GoogleChrome/puppeteer · GitHub)中,中斷 redirect 的標準做法是這樣的:
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();elseinterceptedRequest.continue();});await page.goto('https://example.com');await browser.close(); });這樣一開始也是沒有什么問題,但是偶爾會遇到這樣情況:
Error: net::ERR_FAILED at http://xxx.com/yyy
Google 了一輪,發現相關的 issue 很少,只找到了這么一個:
Page.setRequestInterception Redirection Issue · Issue #3421 · GoogleChrome/puppeteer · GitHub
官方已經把它定義為一個 Bug 了,也有一些相關的解決方案:umbrella Fix Request Interception · Issue #3471 · GoogleChrome/puppeteer · GitHub
不過其他人遇到的情況是 abort() 之后無法結束的問題,而我是拋出異常的問題,所以我自己摸索了一下,總結出一個比較合適的辦法:
就是用 respond 代替 abort。
比如:
// request.abort(); request.respond({status: 404,contentType: 'text/plain',body: 'Not Found!', });總結
以上是生活随笔為你收集整理的puppeteer stop redirect 的正确姿势及 net::ERR_FAILED 的解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 24、springboot与缓存(2)
- 下一篇: SpiderData 2019年2月27