安装
安装浏览器驱动
输入命令后,playwright会自动下载浏览器驱动
第一个代码文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| from playwright.sync_api import sync_playwright
with sync_playwright() as p: browser = p.chromium.launch(headless=False, slow_mo=500) page = browser.new_page() page.goto("https://www.baidu.com") page.screenshot(path="baidu_home.png") browser.close()
print("操作完成")
|
常用元素定位
ID
Name属性
1
| page.locator("[name=wd]")
|
CSS 选择器
id:
class:
XPath 选择器
1
| page.locator("//*[@id='kw']")
|
元素交互
按键操作
1 2
| search_input.press("Enter")
|
勾选复选框/单选框
1 2
| page.locator("#agree").check() page.locator("#agree").uncheck()
|
下拉框选择
1 2 3
| page.locator("#city").select_option(label="北京") page.locator("#city").select_option(value="bj")
|
获取元素文本/属性
1 2 3 4
| kw = page.locator("#kw") print("获取文本:", kw.inner_text())
href = kw.get_attribute("href")
|
悬浮操作
1
| page.locator("#nav-setting").hover()
|
等待
Playwright 内置自动等待机制,会在操作元素前,自动等待元素「可交互」(默认超时 30 秒),无需手动加等待。
- 操作元素(
click()/fill() 等)时,自动等待元素出现、可交互。
- 可手动设置超时时间(如
page.locator("#kw").fill("内容", timeout=10000),10 秒超时)
1 2 3 4 5 6 7 8
| page.locator("#kw").wait_for(state="visible")
page.wait_for_load_state("networkidle")
page.wait_for_function("document.title.includes('测试')")
|
iframe处理
先定位到iframe: page.frame_locator()
1
| iframe = page.frame_locator("iframe[name='rich']")
|
定位内部元素:.locator() 定位 iframe 内部元素
1 2 3
| p = iframe.locator("body > p") text = p.inner_text() print("文本:", text)
|
文件上传
input[type="file"]: 这种直接提交file名称。
1 2
| page.locator("#upload-input").set_input_files("test.jpg") page.locator("#upload-input").set_input_files(["test1.jpg", "test2.pdf"])
|
拖拽上传:
1
| page.locator("#drop-area").set_input_files("test.jpg")
|
穿透影子DOM
直接使用css定位
1
| page.locator("#my-component button.primary").click()
|
断言
安装断言库
1
| pip install playwright-stubs
|
实例
1 2 3 4 5 6 7 8 9 10 11
| from playwright.sync_api import sync_playwright, expect ......
expect(page).to_have_title("百度一下,你就知道")
search = page.locator("#kw") expect(search).to_be_visible() expect(search).to_be_enabled()
expect(page.locator("text=百度一下")).to_be_visible()
|
报告
安装pytest-playwright
1
| pip install pytest-playwright
|
结合pytest使用。