puppeteer: how to wait until an element is visible?

前端 未结 6 1700
粉色の甜心
粉色の甜心 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:22

    You can use page.waitFor(), page.waitForSelector(), or page.waitForXPath() to wait for an element on a page:

    // Selectors
    
    const css_selector = '.btnNext';
    const xpath_selector = '//*[contains(concat(" ", normalize-space(@class), " "), " btnNext ")]';
    
    // Wait for CSS Selector
    
    await page.waitFor(css_selector);
    await page.waitForSelector(css_selector);
    
    // Wait for XPath Selector
    
    await page.waitFor(xpath_selector);
    await page.waitForXPath(xpath_selector);
    

    Note: In reference to a frame, you can also use frame.waitFor(), frame.waitForSelector(), or frame.waitForXPath().

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-01 05:25

    I think you can use page.waitForSelector(selector[, options]) function for that purpose.

    const puppeteer = require('puppeteer');
    
    puppeteer.launch().then(async browser => {
      const page = await browser.newPage();
      page
        .waitForSelector('#myId')
        .then(() => console.log('got it'));
        browser.close();
    });
    

    To check the options avaible, please see the github link.

    0 讨论(0)
  • 2020-12-01 05:40

    Note, All the answers submitted until today are incorrect

    Because it answer for an element if Exist or Located but NOT Visible or Displayed

    The right answer is to check an element size or visibility using page.waitFor() or page.waitForFunction(), see explaination below.

    // wait until present on the DOM
    // await page.waitForSelector( css_selector );
    // wait until "display"-ed
    await page.waitForFunction("document.querySelector('.btnNext') && document.querySelector('.btnNext').clientHeight != 0");
    // or wait until "visibility" not hidden
    await page.waitForFunction("document.querySelector('.btnNext') && document.querySelector('.btnNext').style.visibility != 'hidden'");
    
    const btnNext = await page.$('.btnNext');
    await btnNext.click();
    

    Explanation

    The element that Exist on the DOM of page not always Visible if has CSS property display:none or visibility:hidden that why using page.waitForSelector(selector) is not good idea, let see the different in the snippet below.

    function isExist(selector) {
      let el = document.querySelector(selector);
      let exist = el.length != 0 ? 'Exist!' : 'Not Exist!';
      console.log(selector + ' is ' + exist)
    }
    
    function isVisible(selector) {
      let el = document.querySelector(selector).clientHeight;
      let visible = el != 0 ? 'Visible, ' + el : 'Not Visible, ' + el;
      console.log(selector + ' is ' + visible + 'px')
    }
    
    isExist('#idA');
    isVisible('#idA');
    console.log('=============================')
    isExist('#idB')
    isVisible('#idB')
    .bd {border: solid 2px blue;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="bd">
      <div id="idA" style="display:none">#idA, hidden element</div>
    </div>
    <br>
    <div class="bd">
      <div id="idB">#idB, visible element</div>
    </div>

    on the snippet above the function isExist() is simulate

    page.waitForSelector('#myId');
    

    and we can see while running isExist() for both element #idA an #idB is return exist.

    But when running isVisible() the #idA is not visible or dislayed.

    And here other objects to check if an element is displayed or using CSS property display.

    scrollWidth
    scrollHeight
    offsetTop
    offsetWidth
    offsetHeight
    offsetLeft
    clientWidth
    clientHeight
    

    for style visibility check with not hidden.

    note: I'm not good in Javascript or English, feel free to improve this answer.

    0 讨论(0)
  • 2020-12-01 05:43

    Updated answer with some optimizations:

    const puppeteer = require('puppeteer');
    
    (async() => {
        const browser = await puppeteer.launch({headless: true});
        const page = await browser.newPage();
    
        await page.goto('https://www.somedomain.com', {waitUntil: 'networkidle2'});
        await page.click('input[value=validate]');
        await page.waitForSelector('#myId');
        await page.click('.btnNext');
        console.log('got it');
    
        browser.close();
    })();
    
    0 讨论(0)
  • 2020-12-01 05:46

    If you want to ensure the element is actually visible, you have to use

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

    Otherwise you are just looking for the element in the DOM and not checking for visibility.

    0 讨论(0)
提交回复
热议问题