安装playwight
- 要求:python3.7+
- 安装命令:
pip install playwright
playwright install #安装chrome/firefox等浏览器的驱动文件
录制命令
playwright codegen csdn.net
:打开csdn网站进行录制
playwright codegen --save-storage=auth.json csdn.net
:录制结束时将cookies and localStorage 进行保存在auth.json文件中
playwright codegen --load-storage=auth.json csdn.net
:加载已保存的登录认证信息
playwright codegen -o test.py·
:将录制的文件保存在test.py中
playwright codegen -b ff
:打开firefox浏览器进行录制,默认是chrome,更多参数有: cr, chromium, ff, firefox, wk, webkit
--device="iPhone 11" csdn.net
:#模拟移动设备iPhone11,注意:device的值必须用双引号,并且区分大小写
--viewport-size = 800,600
:设置窗口大小
元素定位
打开录制窗口,在console界面输入以下命名可以判断定位的元素是否准确
playwright.$(selector)
:找出匹配的元素,找到就返回
playwright.$$(selector)
:找出所有匹配的元素
实际操作
控制台下输入playwright codegen www.csdn.net
,进行输入软件测试进行搜索,录制的代码如下
from playwright.sync_api import sync_playwright
def run(playwright):
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
# Open new page
page = context.new_page()
# Go to https://www.csdn.net/
page.goto("https://www.csdn.net/")
# Click [placeholder="git使用"] 录制的脚本使用的placeholder属性,但时此属性的值是每隔几秒就会改边,会导致脚本重放失败,所以改为以下方式定位
page.click("//input[@id='toolbar-search-input']")
# Fill [placeholder="git使用"]
page.fill("//input[@id='toolbar-search-input']", "软件测试")
# Press Enter
# with page.expect_navigation(url="https://so.csdn.net/so/search/all?q=%E8%BD%AF%E4%BB%B6%E6%B5%8B%E8%AF%95&t=all&p=1&s=0&tm=0&lv=-1&ft=0&l=&u="):
with page.expect_navigation():
with page.expect_popup() as popup_info:
page.press("//input[@id='toolbar-search-input']", "Enter")
page1 = popup_info.value
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
参考文档:https://playwright.dev/python/docs/cli