【问题标题】:How to get json data from javascript response in Puppeteer:如何从 Puppeteer 中的 javascript 响应中获取 json 数据:
【发布时间】:2019-12-30 04:47:23
【问题描述】:

我正在使用 Puppeteer 和 Node 编写一个测试,它要求我在登录后从响应中获取访问令牌。

当前代码:

//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());
       }
    });

但是当我这样做时:

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

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

         } catch (error) {

         }
       }
    });

    console.log(object);

我只得到一个承诺。经过大量研究,这是我所得到的。如何从承诺中返回实际的 json 并稍后在我的代码中使用?

【问题讨论】:

  • 尝试在一个变量中捕获这个 await response.json(),然后返回该变量。
  • 我试过了。它返回一个 JS Promise 而不是实际的 JSON。

标签: javascript node.js json automation puppeteer


【解决方案1】:

您需要等待事件侦听器返回承诺。所以代码将是

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

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

         } catch (error) {

         }
       }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2019-12-31
    • 2015-07-02
    • 2021-06-14
    相关资源
    最近更新 更多