我正在修补名为puppeteer
.
我想知道如何收听特定的请求响应以及如何采取行动。
我查看了事件requestfinish
,response
但它为我提供了页面中已经执行的所有请求/响应。
我怎样才能实现评论行为?
谢谢 !
一种选择是执行以下操作:
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
过滤后的响应(最多等待 11 秒)正文解析为 JSON,每次调用时都会使用最初请求的PATCH或POST方法:
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);
由于 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();
我正在使用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')
})
})
要获得 xhr 响应,只需执行以下操作:
const firstResponse = await page.waitForResponse('https://example.com/resource')
// the NEXT line will extract the json response
console.log( await firstResponse.json() )