33

我正在修补名为puppeteer.

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

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

我怎样才能实现评论行为?

谢谢 !

4

5 回答 5

43

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

  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

于 2018-02-07T09:09:51.150 回答
11

过滤后的响应(最多等待 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);
于 2019-08-15T06:28:41.163 回答
5

由于 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();
于 2019-07-01T16:19:39.477 回答
2

我正在使用jest-puppeteer并尝试测试我的测试服务器的特定响应代码。 page.goto() 解析为原始请求的响应

这是一个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')
    })
})
于 2019-04-09T23:25:29.157 回答
0

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

const firstResponse = await page.waitForResponse('https://example.com/resource')

// the NEXT line will extract the json response

console.log( await firstResponse.json() )
于 2021-03-17T07:23:57.997 回答