【问题标题】:Block video requests on puppeteer阻止 puppeteer 上的视频请求
【发布时间】:2019-04-30 20:00:39
【问题描述】:

我想阻止(中止)对视频资源的所有请求,如何使用 puppeteer 实现?

我看到documentation中有一个例子:

一个中止所有图像请求的简单请求拦截器示例:

page.on('request', interceptedRequest => {
    if (interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg'))
      interceptedRequest.abort();
    else
      interceptedRequest.continue();
});

但我似乎找不到有关如何阻止视频的示例。
只有响应标头说content-type,我不想白白浪费带宽。

【问题讨论】:

    标签: javascript node.js google-chrome html5-video puppeteer


    【解决方案1】:

    很好的问题,我自己也有同样的问题。?

    主要问题是视频 URL 不必以特定的后缀结尾,而且实际上在许多网站(例如 YouTube)上也不需要。

    但是有这个功能:

    request.resourceType()

    包含渲染引擎感知的请求资源类型。 ResourceType 将是以下之一:document、stylesheet、image、media、font、script、texttrack、xhr、fetch、eventsource、websocket、manifest、other。

    谷歌搜索了一下,发现了这个MDN

    媒体

    <video><audio> 元素加载的资源。

    而且我也不介意阻止音频请求(感谢上帝,它们并没有在普通网页中使用......)

    最终这就是我最终要做的:

    page.on('request', request => {
      const url = request.url().toLowerCase()
      const resourceType = request.resourceType()
      
      if (resourceType == 'media' ||
        url.endsWith('.mp4') ||
        url.endsWith('.avi') ||
        url.endsWith('.flv') ||
        url.endsWith('.mov') ||
        url.endsWith('.wmv')) {
        
        console.log(`ABORTING: video`)
        request.abort();
      }
      else
        request.continue();
    })
    

    【讨论】:

    • 很确定你还需要await page.setRequestInterception(true);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    相关资源
    最近更新 更多