安装
首先,你需要在Python环境中安装Playwright。使用以下命令进行安装:
pip install playwright
安装完成后,你需要使用以下命令运行来下载所有所需的浏览器二进制文件:
playwright install
代码生成
将代码保存my.py中,用户与登录信息保存到auth.json中:
playwright codegen --save-storage=auth.json -o my.py
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| from playwright import sync_playwright
with sync_playwright() as p: browser = p.chromium.launch() page = browser.newPage() page.goto('https://www.example.com') form = page.querySelector('form') form.fill('username', 'my_username') form.fill('password', 'my_password') form.querySelector('button[type=submit]').click() page.close() browser.close()
|
常用总结
locator 基本操作
基本使用
1 2
| locator = page.locator('.my-selector') locator.click()
|
进行链式操作
1 2
| dropdown = page.locator('.dropdown') dropdown.click().locator('.option').click()
|
在元素下进行进一步的定位
1 2 3
| container = page.locator('.container') button = container.locator('.button') button.click()
|
使用 nth 方法定位特定的元素
1 2
| thirdItem = page.locator('.item').nth(2) thirdItem.click()
|
获取元素的属性和文本
1 2 3
| link = page.locator('.link') href = link.getAttribute('href') text = link.textContent()
|
判断元素是否存在
1 2 3 4 5
| element = page.locator('.my-selector').element_handle() if element is None: print("元素不存在") else: print("元素存在")
|
page.locator 定位页面元素
CSS 选择器
1 2 3 4 5 6
| div_locator = page.locator('div.my-class')
attr_value = div_locator.getAttribute('my-attribute')
text = div_locator.textContent()
|
XPath
1 2 3 4 5 6
| xpath_locator = page.locator('//div[@class="my-class"]')
attr_value = xpath_locator.getAttribute('my-attribute')
text = xpath_locator.textContent()
|
文本
1 2 3 4 5 6
| text_locator = page.locator('text="My Text"')
attr_value = text_locator.getAttribute('my-attribute')
|
打包部署
window环境
1 2 3 4 5 6 7
|
$env:PLAYWRIGHT_BROWSERS_PATH="0" playwright install chromium
pyinstaller -F main.py
|
资源
官网:https://playwright.dev/
python版本:https://playwright.dev/python/docs/intro
api:https://playwright.dev/python/docs/api/class-playwright