【问题标题】:Puppeteer: How to listen to a specific response?Puppeteer:如何聆听特定的回应?
【发布时间】:2021-04-17 15:37:10
【问题描述】:

我正在修改名为 puppeteer 的无头 chrome 节点 API。

我想知道如何监听特定的请求响应以及如何采取相应的行动。

我查看了事件requestfinishresponse,但它为我提供了所有页面中已经执行的请求/响应。

如何实现评论行为?

谢谢!

【问题讨论】:

标签: node.js puppeteer


【解决方案1】:

一种选择是执行以下操作:

  page.on('response', response => {
    if (response.url().endsWith("your/match"))
      console.log("response code: ", response.status());
      // do something here
  });

这仍然会捕获所有请求,但允许您对事件发射器进行过滤和操作。

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#event-response

【讨论】:

    【解决方案2】:

    过滤后的响应(最多等待 11 秒)正文解析为 JSON,每次调用时都会使用初始请求的 PATCHPOST 方法:

    const finalResponse = await page.waitForResponse(response => 
      response.url() === urlOfRequest 
      && (response.request().method() === 'PATCH' 
      || response.request().method() === 'POST'), 11);
    let responseJson = await finalResponse.json();
    console.log(responseJson);
    

    【讨论】:

      【解决方案3】:

      既然 puppeteer v1.6.0(我猜)你可以使用page.waitForResponse(urlOrPredicate[, options])

      文档中的示例用法:

      const firstResponse = await page.waitForResponse('https://example.com/resource');
      const finalResponse = await page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);
      return finalResponse.ok();
      

      【讨论】:

        【解决方案4】:

        我正在使用jest-puppeteer 并尝试测试我的测试服务器的特定响应代码。 page.goto()resolves to the response of the original request

        这是一个简单的测试,即在预期时返回 404 响应。

        describe(`missing article page`, () => {
            let response;
            beforeAll(async () => {
                response = await page.goto('http://my-test-server/article/this-article-does-not-exist')
            })
            it('has an 404 response for missing articles', () => {
                expect(response.status()).toEqual(404)
            })
        
            it('has a footer', async () => {
                await expect(page).toMatch('My expected footer content')
            })
        })
        

        【讨论】:

          【解决方案5】:

          要获得 xhr 响应,只需执行以下操作:

          const firstResponse = await page.waitForResponse('https://example.com/resource')
          
          // the NEXT line will extract the json response
          
          console.log( await firstResponse.json() )
          

          【讨论】:

            猜你喜欢
            • 2012-02-05
            • 1970-01-01
            • 2020-11-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多