puppeteer stop redirect 的正确姿势及 net::ERR_FAILED 的解决

栏目: Node.js · 发布时间: 6年前

内容简介:在官方文档(这样一开始也是没有什么问题,但是偶尔会遇到这样情况:

在官方文档( 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();
    else
      interceptedRequest.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!',
});

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Cracking the Coding Interview

Cracking the Coding Interview

Gayle Laakmann McDowell / CareerCup / 2015-7-1 / USD 39.95

Cracking the Coding Interview, 6th Edition is here to help you through this process, teaching you what you need to know and enabling you to perform at your very best. I've coached and interviewed hund......一起来看看 《Cracking the Coding Interview》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器