gpt4 book ai didi

node.js - Puppeteers waitFor 函数在页面完成渲染之前失败

转载 作者:太空宇宙 更新时间:2023-11-03 23:20:09 27 4
gpt4 key购买 nike

为什么 waitForFunction、waitForSelector、await page.evaluate 等都会给出错误,除非我在阅读页面后延迟 10 秒?

我认为这些是为了等待页面上发生的事情而制作的,但是如果没有我的 10 秒延迟(就在 page.goto 之后) - 所有这些都会因错误而失败。

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://sunnythailand.com')

console.log("Waiting 10 seconds")
await new Promise((resolve)=>setTimeout(()=> resolve() ,10000));
console.log("Here we go....")

console.log("waitForFunction START")
await page.waitForFunction('document.querySelector(".scrapebot_description").textContent.length > 0');
console.log("waitForFunction FOUND scrapebot")

console.log("Waiting for evaluate")
const name = await page.evaluate(() => document.querySelector('.scrapebot_description').textContent)
console.log("Evaluate: " + name)

await browser.close()
})()

我的理论是,我们的 sunnythailand.com 页面在完成渲染之前发送了“页面结束”或其他内容,然后所有 waitFor 函数都变得疯狂并因各种奇怪的错误而失败。

所以我想我的问题是...我们如何让 waitFor 真正等待事件发生或类出现等...?

最佳答案

不要使用超时,因为您不知道加载整个页面需要多长时间。这取决于个人的互联网带宽。

您所需要的一切都依赖于您的类(class)的 promise

等待 page.waitForSelector('.scrapebot_description');让我们等待您的特定类(class),然后它就会正常工作

请删除此内容//等待新的Promise((resolve)=>setTimeout(()=>resolve() ,5000));

请在此之后告诉我您的测试结果。我相信它会解决。

关于node.js - Puppeteers waitFor 函数在页面完成渲染之前失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50804660/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com