【问题标题】:Unable to capture response.json() in playwright无法在剧作家中捕获 response.json()
【发布时间】:2021-07-05 05:31:02
【问题描述】:

我正在尝试使用剧作家捕获 json 响应。我一直在等待 Promise。但是在 headless:false 模式下,我可以看到正在接收数据并在浏览器上填充数据。刚开始玩剧作家,对《无极》也不是很熟悉。

我尝试过的如下:

(async () => {
        let browser = await firefox.launch({headless: true, userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0'});
        let page = await browser.newPage();
        page.waitForResponse(async(response) => {
            if (response.url().includes('/abcd') && response.status() == 200) {
                let resp = await response.json();
                console.log(resp);
            }
        });
        await page.goto('https://myurl.com', {waitUntil: 'networkidle', timeout: 30000});
        await page.waitForTimeout(20000);
        await browser.close();
})

我做错了什么?我试过增加超时。没用。

【问题讨论】:

    标签: javascript webautomation playwright


    【解决方案1】:

    waitForResponse 不会处理您的异步函数。你可以这样做:

    (async () => {
      let browser = await firefox.launch({headless: true, userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0'});
      let page = await browser.newPage();
      const promise page.waitForResponse(/abcd/); // This is a regex to match the url
      await page.goto('https://myurl.com', {waitUntil: 'networkidle', timeout: 30000});
      var response = await promise; // here we wait for the promise to be fullfiled. 
      let resp = await response.json();
      console.log(resp);
      await browser.close();
    })
    

    【讨论】:

    • 谢谢!!工作,更重要的是更好地理解 Promise :)
    猜你喜欢
    • 2021-12-14
    • 2021-06-18
    • 2021-05-16
    • 2022-08-18
    • 2023-02-14
    • 1970-01-01
    • 2021-07-20
    • 2022-11-21
    • 2020-10-08
    相关资源
    最近更新 更多