☰ See All Chapters |
Puppeteer waitForXPath
page.waitForXPath method is used to wait for the element/elements represented by the xpath to appear or to disappear from the page.
waitForXPath( xpath: string, options ?: WaitForSelectorOptions, ): Promise<ElementHandle>; |
Example:
const loginUsername = await page.waitForXPath( "//*[@id='loginUsername']", { visible: true } ); await loginUsername.type( "manu.m@tools4testing.com" ); |
waitForXPath method returns the promise with the element handle which is represented by the selector expression and null if element is not found after timeout, hence it is always better to use waitForXPath method instead of page.$ method.
This waitForXPath method takes two parameters. One is the selector expression and other is the array of options. Below table lists down all those options.
Option | Description |
visible | Puppeteer waits till selector element appears on page, i.e. to not have display: none or visibility: hidden CSS properties. Default value of this option is false. |
hidden | Puppeteer waits till element disappears from page, i.e. have display: none or visibility: hidden CSS properties. Default value of this option is false. |
timeout | This is the maximum time puppeteer wait for the selector. This should be specified in milliseconds. Default value is 30000 (30 seconds). If it is set with 0, timeout option will be discarded. Default 30000 (30 seconds) is the common default timeout value for complete page for any of the timeout needs. This default value can be changed by using the page.setDefaultTimeout(timeout) method. e.g.: page.setDefaultTimeout(5000); |
Puppeteer waitForXPath Example
import { launch, Page } from 'puppeteer'; example(); async function example() { const browser = await launch( { headless: false } ); const page = await browser.newPage(); await page.setViewport( { width: 1500, height: 768 } ); await page.goto( 'https://www.registration.tools4testing.com/' ); await login( page ); await page.waitFor(5000); await browser.close(); }
async function login( page: Page ): Promise<void> { const loginopener = await page.$( "#loginopener" ); loginopener.click(); console.log("Login dialog window opened.") const loginUsername = await page.waitForXPath( "//*[@id='loginUsername']", { visible: true } ); await loginUsername.type( "manu.m@tools4testing.com" ); const loginPassword = await page.waitForXPath("//*[@id='loginPassword']", { visible: true } ); await loginPassword.type("*****"); const loginButton = await page.$( "#loginButton" ); loginButton.click(); const continueLogin = await page.waitForSelector('input[onclick="continueLogin()"] ', {visible : true}); continueLogin.click(); } |
All Chapters