简体   繁体   English

如何从 Puppeteer 的 javascript 响应中获取 json 数据:

[英]How to get json data from javascript response in Puppeteer:

I'm writing a test using Puppeteer and Node which requires me to get an access token from a response after logging in.我正在使用 Puppeteer 和 Node 编写一个测试,它要求我在登录后从响应中获取访问令牌。

Current code:当前代码:

//Click Login Button
    const loginButton = await page.$(".click-button.dark.ng-star-inserted");
    response = await loginButton.click();

    const object = page.on('response', async response =>{
       if(response.url().includes("token")){
          // returns the "access_token" i need
          console.log(await response.json());
       }
    });

But when I do this:但是当我这样做时:

const object = page.on('response', async response =>{
       if(response.url().includes("token")){
         try {

          return JSON.parse(await response.json());

         } catch (error) {

         }
       }
    });

    console.log(object);

I only get a promise.我只得到一个承诺。 After a lot of research this is as far as I've gotten.经过大量研究,这是我得到的。 How can I return the actual json from the promise and leverage later in my code?如何从 promise 返回实际的 json 并稍后在我的代码中使用?

You need to await the event listener as it is returning promise.您需要等待事件侦听器,因为它正在返回承诺。 So code will be所以代码将是

const object = await page.on('response', async response =>{
       if(response.url().includes("token")){
         try {

          return JSON.parse(await response.json());

         } catch (error) {

         }
       }
    });

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

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