安装

首先,你需要在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()
#获取页面内容 获取网页的 HTML 内容
#page.content()
#关闭网页
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
# 通过 CSS 选择器获取元素
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 获取元素
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
#打包前需要设置环境变量、安装浏览器,在环境变量中增加PLAYWRIGHT_BROWSERS_PATH,值为0
#powershell 管理员下执行
$env:PLAYWRIGHT_BROWSERS_PATH="0"
playwright install chromium

#打包命令。执行完成后会在dist出现main.exe
pyinstaller -F main.py

资源

官网:https://playwright.dev/

python版本:https://playwright.dev/python/docs/intro

api:https://playwright.dev/python/docs/api/class-playwright