-
代码生成器:
playwright codegen -o script.py -b chromium (-device iphone11) -
移动端:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
# 指定设备的型号
iphone_12_pro_max = p.devices['iPhone 12 Pro Max']
browser = p.webkit.launch(headless=False)
# 创建上下文(进程执行时的环境资源)
# 初始化
context = browser.new_context(
**iphone_12_pro_max,
locale='zh-CN'
)
# 创建选项卡
page = context.new_page()
# 跳转
page.goto('https://www.whatismybrowser.com/')
# 等待加载完成
page.wait_for_load_state(state='networkidle')
# 截图
# page.screenshot(path='xx')
browser.close()
-
文本选择
page.click("text= Log in") -
CSS选择
# class
page.click('button')
# id
page.click('#nav-bar .contact-us-item')
# 特定值
page.click("[aria-label='Sign in']")
# css+文本
# text包含
page.click('article:has-text("Playwright")') # 选择文本值包含的article节点
# text完全匹配
page.click('#nav-bar :text("Contact us")') # 选择id为nav-bar的节点文本值为
# css+节点关系
page.click('.item-description:has(.item-promo-banner)')
# xpath
page.click('xpath=//button')
- 事件监听
# 监听response事件,将回调方法设置为on_response
# ajax加密也可以返回响应结果
page.on('response', on_response)
-
获得网页源码
page.content() -
页面点击
.click -
文本输入
.fill -
获取节点属性
.get_attribute
.query_selector_all -
获取节点文本
.text_content()