Playwright
Playwright模块提供了启动浏览器实例的方法。以下是使用Playwright驱动自动化的典型示例:
- Sync
- 异步
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())
方法
停止
Added before 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.dev/")
page.screenshot(path="example.png")
browser.close()
playwright.stop()
用法
playwright.stop()
返回
属性
chromium
Added before v1.9该对象可用于启动或连接到Chromium,返回Browser的实例。
用法
playwright.chromium
类型
设备
Added before v1.9返回一个设备字典,用于与browser.new_context()或browser.new_page()一起使用。
- Sync
- 异步
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
Added before v1.9该对象可用于启动或连接到Firefox,返回Browser的实例。
用法
playwright.firefox
类型
请求
Added in: v1.16提供可用于Web API测试的API接口。
用法
playwright.request
类型
选择器
Added before v1.9选择器可用于安装自定义选择器引擎。更多信息请参阅extensibility。
用法
playwright.selectors
类型
webkit
Added before v1.9该对象可用于启动或连接到WebKit,返回Browser的实例。
用法
playwright.webkit
类型