在页面完成渲染之前,Puppeteers waitFor函数失败

时间:2018-06-11 19:19:10

标签: node.js puppeteer

为什么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函数变得疯狂并且因各种奇怪的错误而失败。

所以我想我的问题是......我们如何等待实际上等待事件发生或出现等等......?

1 个答案:

答案 0 :(得分:2)

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

你需要依靠对你班级的承诺

await page.waitForSelector('.scrapebot_description'); 让我们等你的特定班级然后它会正常工作

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

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