如何使用playwright-python收听新页面?
在 JavaScript 中,它将被记录为:
const playwright = require("playwright");
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
context.on("page", async newPage => {
console.log("newPage", await newPage.title())
})
// emulate some opening in a new tab or popup
await page.evaluate(() => window.open('https://google.com', '_blank'))
// Keep in mind to have some blocking action there so that the browser won't be closed. In this case we are just waiting 2 seconds.
await page.waitForTimeout(2000)
await browser.close();
})();
变成 Python
from playwright import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(
headless=False,
executablePath='C:/Program Files/Google/Chrome/Application/chrome.exe'
)
context = browser.newContext()
page = context.newPage()
'''
how to do in Python?
context.on("page", async newPage => {
console.log("newPage", await newPage.title())
})
// emulate some opening in a new tab or popup
await page.evaluate(() => window.open('https://google.com', '_blank'))
'''
page.waitForTimeout(2000)
browser.close()