Puppeteer等待页面加载完成

Puppeteer等待页面加载完成

本文介绍了JS Puppeteer等待页面加载完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到此使用木偶戏的youtube视频玩一下.但是我似乎错误地选择了网站作为入门项目.

After seeing this youtube video using puppeteer I got inspired to play a bit around with it. But I seem to have made the wrong choice of a website as a starter project.

const puppeteer = require('puppeteer')
;(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  await page.goto('http://www.produktresume.dk/AppBuilder/search?page=0')
  page.once('load', () => {
    const drugs = page
      .evaluate(() =>
        [...document.querySelectorAll('div.entity-link')].map(item => item)
      )
      .catch(err => console.log(err))
    console.log(drugs[0])
  })

  await browser.close()
})()

我在Google周围四处搜寻,但对自己尝试过的不同方法都一无所知.

I have googled around and lost track of the different things I have tried..

我对我的问题的看法是,在页面加载时,我没有在正确的时间调用评估.

My perception of my problem is that I don't call the evaluate at the right time - when the page is loaded.

推荐答案

绝对不需要使用page.on('load')来查找是否已加载页面.

There is absolutely no need to use page.on('load') to find if page loaded.

您可以使用

    .goto调用中的
  • waitUntil选项.
  • waitForSelector用于特定选择器的功能.
  • waitUntil option on .goto call.
  • waitForSelector function for specific selector.

用法

await page.goto('http://www.produktresume.dk/AppBuilder/search?page=0', {waitUntil: 'networkidle0'});
await page.waitForSelector("#wrapper"); // Found on the page source code, wait for this to appear
// the rest is just as usual
const drugs = await page
.evaluate(() =>
 [...document.querySelectorAll('div.entity-link')].map(item => item)
)
.catch(err => console.log(err))
console.log(drugs[0])

请确保使用await进行.evaluate通话.

这篇关于JS Puppeteer等待页面加载完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 12:52