简体   繁体   English

操纵人,听网络响应的变化

[英]Puppeteer , listen to network response changes

I am using Puppeteer api ( https://github.com/GoogleChrome/puppeteer ) For automation testing. 我正在使用Puppeteer api( https://github.com/GoogleChrome/puppeteer )进行自动化测试。

I want to listen to all http response, need the url and the response data for each one. 我想听所有http响应,每个URL都需要URL和响应数据。

I try to so use the page.on('response') function : 我尝试使用page.on('response')函数:

 page.on('response', response => {
      response.text().then( textBody=> {
             const req = response.request();;
             console.log(req.url())
             console.log(textBody)
      });
})

Should warp in 'waitForSelector' function , to have a flag that the data is ready? 是否应该在“ waitForSelector”函数中进行扭曲,以标记数据已准备就绪?

I try to do so. 我尝试这样做。

The problem is some time i do not see any console.log and some time i do. 问题是有一段时间我没有看到任何console.log,有一段时间我没有看到。

I will glad to know what do i do wrong? 我很高兴知道我做错了什么?

There is no need to call response.request() , unless you are trying to obtain the URL of the matching request object. 除非您试图获取匹配请求对象的URL,否则无需调用response.request()

The following solution will work just fine: 以下解决方案可以正常工作:

page.on('response', response => {
  console.log('Response URL:', response.url());

  response.text().then(data => {
    console.log('Response Text:');
    console.log(data);
  });
});

If you are still having issues, it could be because the associated request has failed. 如果仍然有问题,可能是因为关联的请求失败。

You can check for this error by listening for the requestfailed event and logging the result: 您可以通过侦听requestfailed事件并记录结果来检查此错误:

page.on('requestfailed', request => {
  console.log('Failed Request URL:', request.url());
  console.log('Failed Request Error Message:', request.failure().errorText);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM