Playwright Automatic Test Common Pocket: This 3 errors are the easiest to overturn.
Playwright Automatic Test Common Pocket: This 3 errors are the easiest to overturn.
Playwright is a modern browser automation tool, but a lot of people step in the process. And today I'm going to take out the three most common mistakes, and I'm going to help you avoid the pits.
Error 1: Operations without waiting for element loading
This is the most common pit. A lot of people write codes that look okay, but run them wrong:element not foundI don't know.
Mistake:
await page.click("#submit-btn");
The problem is that the page may not be loaded and the button does not exist.
Correct practice:
await page.waitForSelector("#submit-btn");
await page.click("#submit-btn");
Or in a more modern way:
await page.locator("#submit-btn").click();
Playwright's locator automatically waits for elements to interact, which is a major advantage over Selenium.
Error 2: Neglected waiting for dynamic loading
Many websites use JavaScript dynamically to render content. Your script may have started extracting data before the contents were loaded.
Mistake:
await page.goto("https://example.com");
const text = await page.textContent(".dynamic-content");
console.log(text); // 可能是 null 或空字符串
Correct practice:
await page.goto("https://example.com");
await page.waitForLoadState("networkidle");
const text = await page.textContent(".dynamic-content");
console.log(text);
Or for specific elements:
await page.locator(".dynamic-content").waitFor({ state: "visible" });
const text = await page.textContent(".dynamic-content");
Error 3: The context and page life cycle of the browser was not processed correctly
Many people create browser examples and forget to turn them off, causing memory leakage. Or shut down the browser at the wrong time, causing the script to collapse.
Mistake:
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto("https://example.com");
// 忘记关闭浏览器
Correct practice:
const browser = await chromium.launch();
try {
const page = await browser.newPage();
await page.goto("https://example.com");
// 你的操作
} finally {
await browser.close();
}
Or in a more elegant way:
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
try {
await page.goto("https://example.com");
// 你的操作
} finally {
await context.close();
await browser.close();
}
Summary
Playwright's core isWaitandLife cycle managementI don't know. Remember these three points:
- Always wait until elements are loaded
- Dynamic content needs to be visible.
- Remember to close the browser and context
This way, 99% of common mistakes can be avoided.