Puppeteer:waitForFunction 未按预期工作

问题描述 投票:0回答:1

我正在使用 Node 和 Puppeteer。

我有一个元素,一旦单击它,文本就会变为“正在生成”,直到下载完成。完成后,文本将更改为其他内容。我正在尝试轮询 1)验证文本切换到“正在生成”(用于验证),然后 2)轮询直到“正在生成”不再存在,表明它已完成并且我可以继续。我已经尝试过以下方法,但似乎都不起作用。

尽管如此,我已经尝试了所有这些孤立的方法(不在 waitForFunction() 内部,并且它们都有效。例如,经过验证的文档...在控制台中有效,等等。

下面是我尝试过的一些事情(为了简洁起见,我没有列出我尝试过的其他事情的详尽列表,其中许多可能甚至没有意义,但我很绝望)。我不包括上面提到的第二步,因为它只是下面代码的逆过程):

await page.waitForFunction('document.querySelector(#rptCol3A1Lnk0_txt).innerText.includes("Generating")')

然后我尝试使用

$eval
,作为 Node 和 Promises 的初学者,我尝试了所有我能想到的等待和返回的组合:

await page.waitForFunction((frame) => frame.$eval("#rptCol3A1Lnk0_txt", el => el.textContent.includes("Generating")),
        {timeout: 5000, polling: 300}, frame)
await page.waitForFunction(async (frame) => {
            return await frame.$eval("#rptCol3A1Lnk0_txt", el => el.textContent.includes("Generating"))
        },
        {timeout: 5000, polling: 300}, frame)
await page.waitForFunction(async (frame) => {
            return frame.$eval("#rptCol3A1Lnk0_txt", el => el.textContent.includes("Generating"))
        },
        {timeout: 5000, polling: 300}, frame)

Puppeteer 文档对于这种方法并不是很有帮助。

javascript node.js promise puppeteer ui-automation
1个回答
0
投票

如果我们只是想查看元素的文本是否已切换为“完成”,我们可以做类似的事情:

 // Define a function that checks the element's text
  const checkTextChange = async () => {
    const element = await page.$('.your-element-selector'); // Replace with your element selector
    if (!element) return false; // Element not found

    const text = await element.evaluate((el) => el.textContent);
    return text === 'Finished'; // Check if the text has changed to "Finished"
  };

  // Wait for the element's text to change to "Finished"
  await page.waitForFunction(checkTextChange, { polling: 'raf', timeout: 30000 });

不确定这是否会完全有帮助,但这应该是一个开始。

© www.soinside.com 2019 - 2024. All rights reserved.