Playwright is a powerful and modern toolset that helps developers automate their web browsers and test their web apps with ease. One of the challenges faced during web scraping or browser automation is handling timeouts. In Playwright, there are several methods to handle timeouts.
1. Using setDefaultTimeout()
You can set a default timeout that applies to all actions using the setDefaultTimeout()
method. This method accepts a single argument, the timeout in milliseconds. Here's how you can use this method:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
page.setDefaultTimeout(5000); // Set default timeout to 5000ms or 5 seconds
await browser.close();
})();
2. Setting timeout in individual commands
Playwright allows setting timeout values in individual commands. This could be useful when you want a specific action to wait for a longer or shorter time than the default.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com', {timeout: 6000}); // Set timeout to 6000ms for this action
await browser.close();
})();
3. Using waitForTimeout()
The waitForTimeout()
function can be used when you want your Playwright script to do nothing for a specified period. This is similar to using sleep
function in other programming languages.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.waitForTimeout(3000); // Wait for 3000ms or 3 seconds
await browser.close();
})();
4. Using context.setDefaultTimeout()
The setDefaultTimeout()
method can also be used at the browser context level. This will apply the specified timeout to all pages and frames associated with the context.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
context.setDefaultTimeout(4000); // Set default timeout to 4000ms for this context
const page = await context.newPage();
await browser.close();
})();
5. Setting timeout in page.waitForNavigation()
You can also set a timeout for page navigation. This will wait for the navigation to complete within the specified time.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.waitForNavigation({ timeout: 7000 }); // Set timeout to 7000ms for this navigation
await browser.close();
})();
Remember, all these timeout values are in milliseconds. So, 1000 milliseconds equals 1 second. Adjust these values according to your requirements.