我尝试寻找这个答案,但互联网上似乎没有答案。我想要做的是使用 Node js 重新加载页面,直到找到带有我想要的查询的元素。如果有帮助的话,我将在程序的其他部分使用 puppeteer。
好吧,我使用了两个答案中的函数并提出了这个,可能是未优化的代码:
const puppeteer = require("puppeteer");
(async () => {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("http://127.0.0.1:5500/main.html");
await page.waitForSelector("#buy-button");
console.log("worked");
} catch (err) {
console.log(`ERROR: ${err}`);
}
})();
但是我不知道该怎么做,就是重新加载页面,并不断重新加载,直到出现我想要的 id。例如,不断重新加载 youtube,直到出现您想要的视频(不切实际的例子,但我认为它能说明问题)。
最佳答案
以下是我如何解决等待 puppeteer 中的元素并在未找到时重新加载页面的问题;
async waitForSelectorWithReload(selector: string) {
const MAX_TRIES = 5;
let tries = 0;
while (tries <= MAX_TRIES) {
try {
const element = await this.page.waitForSelector(selector, {
timeout: 5000,
});
return element;
} catch (error) {
if (tries === MAX_TRIES) throw error;
tries += 1;
void this.page.reload();
await this.page.waitForNavigation({ waitUntil: 'networkidle0' });
}
}
}
并且可以用作;
await waitForSelectorWithReload("input#name")
关于javascript - 如何重新加载并等待元素出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64948077/