Python Playwright:Locator 元素操作详解
Python:Playwright之元素操作方法大全
前言
在使用 Playwright 进行 Web 自动化测试或爬虫开发时,元素操作是非常重要的一部分。Playwright 提供了强大的定位器(Locator)功能,用于准确、可靠地定位页面上的各种元素,例如文本框、按钮、下拉框等。本文将深入介绍 Playwright 中 Locator 的常用方法,帮助读者更好地理解和应用这一功能。
Locator 常用方法
查找元素
使用 page.locator()
方法创建一个定位器,通过这个定位器可以执行各种操作。
定位元素
查找页面上所有匹配的元素
page.locator(selector).all()
获取匹配元素集合中的第n个元素
page.locator(selector).nth(index)
在第一个定位器找到的元素中继续定位子元素
page.locator(selector).locator(selector)
获取框架内的元素定位器
page.frame("frame_name").locator(selector)
page.frame_locator("frame_id").locator(selector)
根据条件过滤匹配的元素
参数说明:
has_text:筛选包含指定文本的元素,匹配元素内或子元素中的文本内容。
has_not_text:筛选不包含指定文本的元素。
has:筛选包含指定相对定位器(Locator)匹配的元素,内部定位器必须相对于外部定位器。
has_not:筛选不包含指定相对定位器匹配的元素。
返回值:
返回一个新的 Locator 对象,表示经过筛选条件处理后的定位器。
代码示例:
# 创建一个行定位器
row_locator = page.locator("tr")
# 使用 filter 方法进行筛选
row_locator.filter(has_text="text in column 1").filter(
has=page.get_by_role("button", name="column 2 button")
).screenshot()
or_
该方法用于创建一个新的定位器(Locator),该定位器可以匹配当前定位器或指定的另一个定位器(locator)中的任意一个条件。
# 获取页面上具有 'New' 角色且名称为 'New email' 的按钮,或者包含文本 'Confirm security settings' 的对话框
new_email = page.get_by_role("button", name="New")
dialog = page.get_by_text("Confirm security settings")
expect(new_email.or_(dialog)).to_be_visible()
if dialog.is_visible():
page.get_by_role("button", name="Dismiss").click()
new_email.click()
and_
该用于创建一个新的定位器(Locator),该定位器同时匹配当前定位器和指定的另一个定位器(locator)。
# 获取页面上具有 'button' 角色的元素,并且标题为 'Subscribe' 的按钮
button = page.get_by_role("button").and_(page.getByTitle("Subscribe"))
元素操作
点击元素
参数说明:
modifiers(可选):指定要在点击操作期间按下的键盘修饰键。
可以包括以下值之一或多个组合:
“Alt”:按下 Alt 键
“Control”:按下 Ctrl 键
“Meta”:按下 Meta 键(通常是 Command 键或 Windows 键)
“Shift”:按下 Shift 键
position(可选):指定点击操作相对于元素左上角的位置。
delay(可选):鼠标按下和释放之间的等待时间(以毫秒为单位)。
button(可选):指定用于点击操作的鼠标按钮类型(包括 “left”、“middle” 和"right"。默认为 “left”)。
click_count(可选):指定要点击的次数。
timeout(可选):等待点击操作完成的最大时间(以毫秒为单位,默认 30000 毫秒)。
force(可选):指定是否绕过元素可操作性检查。
no_wait_after(可选):指定是否等待由点击操作引发的导航完成。
trial(可选):指定是否仅执行操作可行性检查而跳过实际点击操作。
page.locator(selector).click()
双击元素
page.locator(selector).dblclick()
悬停在元素上
page.locator(selector).hover()
在输入框中输入文本
page.locator(selector).fill('your_text')
截取元素的屏幕截图
page.locator(selector).screenshot()
清空输入框中的文本
page.locator(selector).clear()
高亮元素
page.locator(selector).highlight()
选中复选框或单选按钮
page.locator(selector).check()
设置复选框或单选按钮的选中状态
page.locator(selector).set_checked(checked=True) # True(选中) False (取消选中)
取消选中复选框或单选按钮
page.locator(selector).uncheck()
触发元素的失焦事件
page.locator(selector).blur()
让元素获取焦点
page.locator(selector).focus()
轻触元素
page.locator(selector).tap()
滚动元素到可见区域
page.locator(selector).scroll_into_view_if_needed()
将元素拖拽到另一个位置
source = page.locator(\"#source\")
target = page.locator(\"#target\")
source.drag_to(target)
模拟按键按下事件
page.locator(selector).press('Enter')
Web API 中键盘事件 key 值的参考文档:https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
按顺序按下一系列按键
page.locator(selector).press_sequentially(\"my password\")
触发元素的失焦事件
page.locator(selector).blur()
选择下拉列表中的选项
该方法可用于在 < select > 元素中进行选项选择操作,支持按值、索引或标签选择单个或多个选项。确保在使用此方法之前,已经准确地定位到了要操作的< select >元素。
1.使用 value 参数按照选项的值来选择选项。
# 单个值选择
page.locator('select').select_option(value='blue')
# 多个值选择(适用于具有 multiple 属性的 <select> 元素)
page.locator('select').select_option(value=['red', 'green', 'blue'])
2.使用 index 参数按照选项在 < select > 元素中的索引来选择选项。索引从 0 开始,表示第一个选项。
# 单个索引选择
page.locator('select').select_option(index=2) # 选择第三个选项
# 多个索引选择
page.locator('select').select_option(index=[0, 2, 4]) # 选择第一个、第三个和第五个选项
3.使用 label 参数按照选项的文本标签来选择选项。
# 单个标签选择
page.locator('select').select_option(label='Blue') # 选择文本标签为 "Blue" 的选项
# 多个标签选择(适用于具有 multiple 属性的 <select> 元素)
page.locator('select').select_option(label=['Red', 'Green', 'Blue']) # 选择文本标签为 "Red"、"Green" 和 "Blue" 的选项
选择文本
page.locator(selector).select_text() 方法用于在元素中选择所有文本内容。
该方法会等待元素变得可操作,然后将焦点放在元素上,并选择其全部文本内容。
page.locator('textarea').select_text() # 选择指定定位器的元素的所有文本内容
标准文件上传
page.locator(selector).set_input_files()
# 上传单个文件
page.locator(selector="input[type=file]").set_input_files('myfile.pdf')
# 上传多个文件:
page.locator(selector="input[type=file]").set_input_files(['file1.txt', 'file2.txt'])
# 清除已选择的文件:
page.locator(selector="input[type=file]").set_input_files([])
# 从内存中上传文件(使用 FilePayload):
page.locator(selector="input[type=file]").set_input_files(
files=[{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}],
)
对页面元素执行 JavaScript 代码
page.locator(selector).evaluate()
对选定的所有元素执行 JavaScript 代码,并返回结果
page.locator(selector).evaluate_all()
在页面上下文中执行JavaScript代码,并返回句柄
evaluate_handle 方法用于在页面中执行 JavaScript 代码,并将匹配的元素作为第一个参数传递给表达式,并返回一个 JSHandle,其中包含表达式的结果。
参数说明:
expression:要在浏览器上下文中执行的 JavaScript 表达式。如果表达式求值为一个函数,则该函数会自动调用,并且第一个参数将是匹配的元素。
arg:可选参数,传递给表达式的第二个参数。
timeout:可选参数,指定执行 JavaScript 代码的最长等待时间(以毫秒为单位)。
该方法与 locator.evaluate() 的区别在于,evaluate_handle() 返回一个 JSHandle,而不是直接返回表达式的结果。
如果表达式返回一个 Promise,该方法将等待 Promise 解析,并返回其值。如果表达式抛出异常或拒绝 Promise,该方法将抛出相应的错误。
返回值:
返回一个 JSHandle 对象,其中包含 JavaScript 表达式的结果。可以通过 JSHandle 对象获取 JavaScript 表达式的返回值或进一步操作。
# 获取匹配的元素,并使用 evaluate_handle 执行 JavaScript 表达式
element_handle = page.locator("button").evaluate_handle("element.textContent")
# 使用 arg 参数传递额外的参数给 JavaScript 表达式
result_handle = page.locator("#myElement").evaluate_handle("document.querySelector(selector).textContent", arg="#myElement")
该方法在浏览器自动化中非常有用,可以通过执行 JavaScript 代码来获取元素的属性、内容或执行其他操作,从而实现更灵活和复杂的页面交互和数据提取。
分发自定义事件到元素
dispatch_event方法用于在匹配的元素上程序化地触发指定类型的事件。
page.locator.dispatch_event("click")
上述示例中,dispatch_event 方法会在匹配的元素上触发 click 事件,就像调用 element.click() 一样。无论元素的可见状态如何,都会触发相应的事件。
添加定位器处理程序
用于处理在测试过程中出现意外覆盖层或对话框。当检测到特定的弹框标题时,自动点击弹框中的按钮。(可以注册多个处理程序,但一次只能运行一个处理程序)
page.add_locator_handler(
page.get_by_role("heading", name=heading),
lambda: page.get_by_role("button", name=button).click(),
)
元素信息获取
获取元素的文本内容
page.locator(selector).text_content()
获取元素的属性值
page.locator(selector).get_attribute('attribute_name')
获取输入框中的值
page.locator(selector).input_value()
获取元素的边界框
page.locator(selector).bounding_box()
获取元素的内部 HTML
page.locator(selector).inner_html()
获取元素的内部文本
page.locator(selector).inner_text()
获取所有匹配元素的内部文本
page.locator(selector).all_inner_texts()
获取所有匹配元素的文本内容
page.locator(selector).all_text_contents()
计算匹配元素的数量
page.locator(selector).count()
其他操作
检查元素状态
page.locator(selector).is_xxx() 方法将检查第一个匹配元素是否被选中,并返回布尔值 True 或 False。
该方法通常用于快速检查元素的可见性,不会进行等待操作,立即返回结果。
page.locator(selector).is_checked() # 检查元素是否被选中
page.locator(selector).is_disabled() # 检查元素是否被禁用
page.locator(selector).is_editable() # 检查元素是否可编辑
page.locator(selector).is_enabled() # 检查元素是否可用
page.locator(selector).is_hidden() # 检查元素是否隐藏
page.locator(selector).is_visible() # 检查元素是否可见
作者:blues_C