Playwright
Playwright 模块提供了一种启动浏览器实例的方法。以下是使用 Playwright 驱动自动化的典型示例
- 同步
- 异步
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
chromium = playwright.chromium # or "firefox" or "webkit".
browser = chromium.launch()
page = browser.new_page()
page.goto("http://example.com")
# other actions...
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
chromium = playwright.chromium # or "firefox" or "webkit".
browser = await chromium.launch()
page = await browser.new_page()
await page.goto("http://example.com")
# other actions...
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
方法
stop
在 v1.9 之前添加如果 Playwright 实例是在绕过 Python 上下文管理器的情况下创建的,则终止该实例。这在 REPL 应用程序中很有用。
from playwright.sync_api import sync_playwright
playwright = sync_playwright().start()
browser = playwright.chromium.launch()
page = browser.new_page()
page.goto("https://playwright.net.cn/")
page.screenshot(path="example.png")
browser.close()
playwright.stop()
用法
playwright.stop()
返回值
属性
chromium
在 v1.9 之前添加此对象可用于启动或连接到 Chromium,并返回 Browser 的实例。
用法
playwright.chromium
类型
devices
在 v1.9 之前添加返回一个设备字典,用于 browser.new_context() 或 browser.new_page()。
- 同步
- 异步
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
webkit = playwright.webkit
iphone = playwright.devices["iPhone 6"]
browser = webkit.launch()
context = browser.new_context(**iphone)
page = context.new_page()
page.goto("http://example.com")
# other actions...
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
webkit = playwright.webkit
iphone = playwright.devices["iPhone 6"]
browser = await webkit.launch()
context = await browser.new_context(**iphone)
page = await context.new_page()
await page.goto("http://example.com")
# other actions...
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
用法
playwright.devices
类型
firefox
在 v1.9 之前添加此对象可用于启动或连接到 Firefox,并返回 Browser 的实例。
用法
playwright.firefox
类型
request
添加于:v1.16公开可用于 Web API 测试的 API。
用法
playwright.request
类型
selectors
在 v1.9 之前添加选择器可用于安装自定义选择器引擎。有关更多信息,请参阅 可扩展性。
用法
playwright.selectors
类型
webkit
在 v1.9 之前添加此对象可用于启动或连接到 WebKit,并返回 Browser 的实例。
用法
playwright.webkit
类型