playwright常用方法

一、常用 API

1.1 认证信息保存

from playwright.sync_api import sync_playwright,expect  
  
with sync_playwright() as p:  
  
    browser = p.chromium.launch(  
        headless=False,  
        channel='chrome',  
        args=['--start-maximized'],  
    )  
    context = browser.new_context(  
        no_viewport=True,  
    )  
    page = context.new_page()  
    page.goto('http://124.223.40.245:83/index.php/Home/user/login.html')  
  
    page.get_by_placeholder('手机号/邮箱').fill("13800138006")  
    page.get_by_placeholder('密码').fill("123456")  
    page.get_by_placeholder('验证码').fill("8888")  
    page.locator(".J-login-submit").click()  
    expect(page.locator('a[title="退出"]')).to_be_visible()  
  
    #保存网站登录信息  
    storage = context.storage_state(path="shop_state.json")

1.2 认证信息读取

from playwright.sync_api import sync_playwright,expect  
import re  
  
with sync_playwright() as p:  
  
    browser = p.chromium.launch(  
        headless=False,  
        channel='chrome',  
        args=['--start-maximized'],  
    )  
    context = browser.new_context(  
        no_viewport=True,  
        storage_state="shop_state.json",  #读取已经保存好的登录信息  
    )  
    page = context.new_page()  
    page.goto('http://124.223.40.245:83/index.php/Home/Order/order_list.html')  
    expect(page).to_have_title(re.compile('我的订单'))

1.3 常用方法

1. 创建浏览器对象
	browser = p.chromium.launch(  
	    headless=False,  
	    channel='chrome',  
	    args=['--start-maximized'],  
	)
2. 创建上下文管理器
	context = browser.new_context(  
    no_viewport=True,  
    storage_state="shop_state.json",  #读取已经保存好的登录信息  
	)
3. 创建页面
	1. page = context.new_page()
4. 打开网址
	1. page.goto('http://124.223.40.245:83/index.php/Home/User/address_list.html')  
	expect(page).to_have_title(re.compile('地址管理'))
5. 等待,单位是毫秒
	1. page.wait_for_timeout(500)
6. 定位器
	1. page.locator('#address_submit')
7. 点击操作
	1. click()
8. 输入文本
	1. fill(value='修改最后一个')
9. 将元素滚动到试图中
	1. locator.scroll_into_view_if_needed()
	2. locator.scroll_into_view_if_needed(**kwargs)
10. page.pause()
	1. 暂停操作,可以调试

二、查找元素

2.1 查找单个元素

  1. page.locator(".address.co_blue") 获取元素
  2. 如果获取的是多个元素,使用 firstlast 进行选取第一个或者最后一个
from playwright.sync_api import sync_playwright,expect  
import re  
  
with sync_playwright() as p:  
  
    browser = p.chromium.launch(  
        headless=False,  
        channel='chrome',  
        args=['--start-maximized'],  
    )  
    context = browser.new_context(  
        no_viewport=True,  
        storage_state="shop_state.json",  #读取已经保存好的登录信息  
    )  
    page = context.new_page()  
  
    # 前往地址管理  
    page.goto('http://124.223.40.245:83/index.php/Home/User/address_list.html')  
    expect(page).to_have_title(re.compile('地址管理'))  
    #定位地址的修改按钮  
    address = page.locator(".address.co_blue")  
    #第一个地址的修改按钮  
    address.first.click()  
    page.wait_for_timeout(500)  
    #修改详细信息  
    page.locator('input[placeholder="详细地址"]').fill(value='修改第一个')  
    #点击保存按钮  
    page.locator('#address_submit').click()  
    expect(page.locator('//*[text()="修改第一个"]'))  
    # 最后一个地址的修改按钮  
    address.last.click()  
    page.wait_for_timeout(500)  
    # 修改详细信息  
    page.get_by_placeholder('详细地址').fill(value='修改最后一个')  
    # 点击保存按钮  
    page.locator('#address_submit').click()  
    expect(page.locator('//*[text()="修改最后一个"]'))

2. 2 查找多个元素

#获取元素,当有多个元素时,获取第1个,如果没有元素,返回 None
ele1 = page.query_selector('.address_delete.co_blue')   

#获取元素,当有多个元素时,获取所有的元素,返回的是列表,如果没有获取到元素,返回 空列表[]
ele2 = page.query_selector_all('.address_delete.co_blue')  

三、常见的页面元素操作

3.1 文本输入

1. 文本输入
page.fill("id=kw", "test")

2. 一个字符一个字符的输入,模拟真实的键盘输入
page.type("id=kw", "playwright")
page.type("id=kw", "playwright", delay=100): 每个字符延迟100ms输入

3. 支持各种键盘事件,比如Tab、Delete、Enter、PageDown、PageUp、F1 - F12、0-9、A-Z等
page.press("id=kw", '@') : 模拟键盘输入 `@` 符号
page.press("id=kw", 'Control+A'`:Control+A
page.press('id=kw', 'Enter'):点击回车

3.2 鼠标点击

page.get_by_text(“我的购物车”).hover()

左键点击:page.click("id=su")
点击元素左上角:page.click('id=su', position={'x': 0, 'y': 0})
Shift + click:page.click("id=su", modifiers=['Shift'])
强制点击:page.click("id=su", force=True)
右键点击:page.click("id=su", button='right')
双击:page.dblclick("id=su")
悬停在元素上:page.hover('id=su')

3.3 下拉框

  1. 根据文本定位:select_option(label=“北京市”)
  2. 根据 value 属性定位:select_option(value=“2”)
  3. 根据下标定位:select_option(index=1)
page.locator("#province").select_option(label="北京市")  
page.locator("#city").select_option(value="2")  
page.locator("#district").select_option(value="3")  
page.locator("#twon").select_option(index=1)

3.4 文件上传

1. 上传单张图片
page.locator("#filePicker input").set_input_files(r"E:\tang\Desktop\tf102项目\系统测试-tpshop\唐柳林\流程图.jpg")

2. 上传多张图片
page.locator("#filePicker input").set_input_files(['file1.txt', 'file2.txt'])

3. 清除图片
page.locator("#filePicker input").set_input_files([])

3.5 日期框操作

page.locator(‘input[name=“apply.start_time”]’).evaluate(‘node => node.value=“2023-04-16 20:00”’)
page.locator(‘input[name=“apply.end_time”]’).evaluate(‘node => node.value=“2023-04-16 23:00”’)

执行 js 语句:
page.locator(‘input[name=“apply.start_time”]’).evaluate(‘el => el.value="2023-04-16 20:00 "’)

from playwright.sync_api import sync_playwright, expect  
  
with sync_playwright() as p:  
    browser = p.chromium.launch(  
        headless=False,  
        channel='chrome',  
        args=['--start-maximized'],  
    )  
    context = browser.new_context(  
        no_viewport=True,  
        storage_state="shop_state.json",  
    )  
  
    page = context.new_page()  
    page.goto("http://124.223.40.245:8080/woniuboss")  
    page.get_by_placeholder("请输入用户名").fill("admin")  
    page.get_by_placeholder("请输入密码").fill("woniu123")  
    page.fill('input[name="checkcode"]', "0000")  
    if not page.locator('input[checked="checked"]'):  
        page.click('input[checked="checked"]')  
    page.get_by_text("登录").click()  
    page.get_by_role("link", name="教学管理").click()  
    page.get_by_role("link", name="加班申请").click()  
    page.get_by_role("button", name="新增").click()  

	#处理日期框
    page.locator('input[name="apply.start_time"]').evaluate('node => node.value="2023-04-16 20:00"')  
    page.locator('input[name="apply.end_time"]').evaluate('node => node.value="2023-04-16 23:00"')  
    
    page.locator('select[name="apply.accounting_way"]').select_option(label="结算工资")  
    page.locator('select[name="apply.hours"]').select_option(label="3小时")  
    page.locator('select[name="apply.region_id"]').select_option(value="4")  
    text = "上班很累,加班很爽,模拟面试"  
    page.locator('textarea[name="apply.reason"]').fill(text)  
    page.get_by_text("提交申请").click()  
    page.wait_for_selector('.bootbox-body')  
    page.get_by_role('button', name="确定").click()

3.6 元素等待

page.wait_for_event("event", event_predict, timeout)
page.wait_for_function(js_function)
page.wait_for_load_state(state="domcontentloaded|load|networkidle", timeout)
page.wait_for_selector(selector, timeout)
page.wait_for_timeout(timeout)  # 不推荐使用

3.7 javascript 弹框

alert(), confirm(), prompt() dialogs

page.on("dialog", lambda dialog: dialog.accept())
page.get_by_role("button").click()

page.on("dialog", lambda dialog: print(dialog.message))
page.get_by_role("button").click() # Will hang here

def handle_dialog(dialog):
    assert dialog.type == 'beforeunload'
    dialog.dismiss()

page.on('dialog', lambda: handle_dialog)
page.close(run_before_unload=True)

3.8 iframe 操作

page.frame_locator("iframe[name^=\"layui-layer-iframe\"]").get_by_text("确定使用").click()

3.9 验证码操作

3.10 截图

1. 截取页面
page.goto("https://www.baidu.com/")
# 方法1
page.screenshot(path="screenshot1.png")
# 方法2
page.screenshot(path="screenshot2.png", full_page=True)
# 方法3:
screenshot_bytes = self.page.screenshot()
open("screenshot3.png", "wb").write(screenshot_bytes)

2. 截取元素
element_handle = self.page.query_selector("id=su")
element_handle.screenshot(path="baidu.png")

3.11 视频录制

#一定要关闭 context

context = browser.new_context(  
    no_viewport=True,  
    storage_state="shop_state.json",  
    record_video_dir="./videos",   #指定视频放置文件夹
    #record_video_size={"width": 1920, "height": 1080},  # 指定视频录制大小  
)

video_path = page.video.path()  #获取视频路径 videos\b126cee45e43983e1f0cd7ad3ff27cac.webm
print(video_path)  
page.close()  
context.close()  
browser.close()

3.12 断言

expect(locator).to_be_checked()			Checkbox is checked
expect(locator).to_be_disabled()		Element is disabled
expect(locator).to_be_editable()		Element is enabled
expect(locator).to_be_empty()			Container is empty   
expect(locator).to_be_enabled()			Element is enabled
expect(locator).to_be_focused()			Element is focused
expect(locator).to_be_hidden()			Element is not visible
expect(locator).to_be_visible()			Element is visible
expect(locator).to_contain_text()		Element contains text
expect(locator).to_have_attribute()		Element has a DOM attribute
expect(locator).to_have_class()			Element has a class property
expect(locator).to_have_count()			List has exact number of children
expect(locator).to_have_css()			Element has CSS property
expect(locator).to_have_id()			Element has an ID
expect(locator).to_have_js_property()	Element has a JavaScript property
expect(locator).to_have_text()			Element matches text
expect(locator).to_have_value()			Input has a value
expect(locator).to_have_values()		Select has options selected
expect(page).to_have_title()			Page has a title
expect(page).to_have_url()				Page has a URL
expect(api_response).to_be_ok()			Response has an OK status

3.14 新窗口处理

with context.expect_page() as page_info:  
    page.get_by_role("link", name="我的订单").click()  
page1 = page_info.value  
page1.wait_for_load_state()

3.15 选框处理

勾选:`page.check('#agree')`
取消勾选:`page.uncheck('#agree')`
判断是否勾选:`page.is_checked('#agree')`  #返回布尔值

3.16 获取元素属性

读取属性:`get_attribute(selector, attr_name)`

-------------------返回布尔值-------------------
元素是否可见:`is_visible(selector)`
元素是否可用:`is_enabled(selector)`
是否勾选:`page.is_checked(selector)`
inner text判断:page.inner_text('#s-top-left:has(a) > a:nth-child(2)')
文本内容判断:page.text_content('#s-top-left:has(a) > a:nth-child(2)')

你可能感兴趣的:(UI自动化,python,pytest)