puppeteer: how to wait until an element is visible?

前端 未结 6 1704
粉色の甜心
粉色の甜心 2020-12-01 05:22

I would like to know if I can tell puppeteer to wait until an element is displayed.

const inputValidate = await page.$(         


        
6条回答
  •  隐瞒了意图╮
    2020-12-01 05:23

    While I agree with @ewwink answer. Puppeteer's API checks for not hidden by default, so when you do:

    await page.waitForSelector('#id', {visible: true})
    

    You get not hidden and visible by CSS. To ensure rendering you can do as @ewwink's waitForFunction. However to completely answer your question, here's a snippet using puppeteer's API:

    async waitElemenentVisble(selector) {
      function waitVisible(selector) {
        function hasVisibleBoundingBox(element) {
          const rect = element.getBoundingClientRect()
          return !!(rect.top || rect.bottom || rect.width || rect.height)
        }
        const elements = [document.querySelectorAll(selector)].filter(hasVisibleBoundingBox)
        return elements[0]
      }
      await page.waitForFunction(waitVisible, {visible: true}, selector)
      const jsHandle = await page.evaluateHandle(waitVisible, selector)
      return jsHandle.asElement()
    }
    

    After writing some methods like this myself, I found expect-puppeteer which does this and more better (see toMatchElement).

提交回复
热议问题