When working with Playwright, you might encounter various types of errors and exceptions due to network issues, browser crashes, misconfigured scripts, etc. Handling these errors and exceptions properly is crucial for developing a robust scraping or automation script.
Python
In Python, you can handle exceptions using try/except blocks. Here's an example of how to handle errors in Playwright:
from playwright.sync_api import sync_playwright
try:
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://www.example.com")
# If the element is not present, Playwright will raise an error
try:
page.click("#nonexistent-button")
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
browser.close()
In the above example, we're trying to click a button that doesn't exist on the page. Playwright will raise an exception, which we then catch and handle by simply printing an error message.
JavaScript
In JavaScript, you can handle exceptions using try/catch blocks. Here's an example of how to handle errors in Playwright:
const playwright = require('playwright');
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://www.example.com');
try {
// If the element is not present, Playwright will throw an error
await page.click('#nonexistent-button');
} catch (error) {
console.error(`An error occurred: ${error.message}`);
} finally {
await browser.close();
}
})();
In the above example, we're trying to click a button that doesn't exist on the page. Playwright will throw an exception, which we then catch and handle by simply printing an error message.
Remember, handling errors and exceptions is very important as it helps in identifying what went wrong in the script and also prevents the script from breaking. Therefore, always include error handling in your Playwright scripts.