拦截某个请求并得到它的响应(puppeteer) [英] Intercept a certain request and get its response (puppeteer)

查看:22
本文介绍了拦截某个请求并得到它的响应(puppeteer)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦 puppeteer 转到某个 url,我希望它监听所有发出的请求,然后找到一个特定的请求并返回它的响应.响应应该是一个 json 对象.

Once that puppeteer goes to a certain url, I want that it listens to all the requests that are made, then find a specific request and return its response. The response should be a json object.

我设法侦听了所有请求并拦截了所需的请求,但我不知道如何获得其响应.这是我的尝试:我收到错误 TypeError: Cannot read property 'then' of null.

I managed in listening to all the requests and intercepting the desired one, but I don't know how to get its response. Here's my attempt: I get the error TypeError: Cannot read property 'then' of null.

有什么建议吗?

page.on('request',async(request)=>{
    console.log(request.url())

    if (request.url().includes('desiredrequest.json')){
        console.log('Request Intercepted')
        request.response().then(response => {
            return response.text();
        }).then(function(data) {
        console.log(data); // this will be a string
        alert(data)
        });
    }

    request.continue()
})

推荐答案

由于响应可能还没有到达,更好的方法是监听 response 事件并从中获取请求对象.

Since the response may have not arrived yet, the better method would be listening on the response event and get the request object from it.

page.on('response', async(response) => {
    const request = response.request();
    if (request.url().includes('desiredrequest.json')){
        const text = await response.text();
        console.log(text);
    }
})

这篇关于拦截某个请求并得到它的响应(puppeteer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆