操作
简介
Playwright 可以与 HTML 输入元素进行交互,例如文本输入、复选框、单选按钮、选择选项、鼠标点击、输入字符、按键和快捷键,以及上传文件和聚焦元素。
文本输入
使用 locator.fill() 是填充表单字段最简单的方法。它会聚焦元素并触发一个带有输入文本的 input 事件。它适用于 <input>、<textarea> 和 [contenteditable] 元素。
- 同步
- 异步
# Text input
page.get_by_role("textbox").fill("Peter")
# Date input
page.get_by_label("Birth date").fill("2020-02-02")
# Time input
page.get_by_label("Appointment time").fill("13:15")
# Local datetime input
page.get_by_label("Local time").fill("2020-03-02T05:15")
# Text input
await page.get_by_role("textbox").fill("Peter")
# Date input
await page.get_by_label("Birth date").fill("2020-02-02")
# Time input
await page.get_by_label("Appointment time").fill("13:15")
# Local datetime input
await page.get_by_label("Local time").fill("2020-03-02T05:15")
复选框和单选按钮
使用 locator.set_checked() 是选中和取消选中复选框或单选按钮最简单的方法。此方法可用于 input[type=checkbox]、input[type=radio] 和 [role=checkbox] 元素。
- 同步
- 异步
# Check the checkbox
page.get_by_label('I agree to the terms above').check()
# Assert the checked state
expect(page.get_by_label('Subscribe to newsletter')).to_be_checked()
# Select the radio button
page.get_by_label('XL').check()
# Check the checkbox
await page.get_by_label('I agree to the terms above').check()
# Assert the checked state
await expect(page.get_by_label('Subscribe to newsletter')).to_be_checked()
# Select the radio button
await page.get_by_label('XL').check()
选择选项
使用 locator.select_option() 选择 <select> 元素中的一个或多个选项。您可以指定选项的 value 或 label 进行选择。可以选择多个选项。
- 同步
- 异步
# Single selection matching the value or label
page.get_by_label('Choose a color').select_option('blue')
# Single selection matching the label
page.get_by_label('Choose a color').select_option(label='Blue')
# Multiple selected items
page.get_by_label('Choose multiple colors').select_option(['red', 'green', 'blue'])
# Single selection matching the value or label
await page.get_by_label('Choose a color').select_option('blue')
# Single selection matching the label
await page.get_by_label('Choose a color').select_option(label='Blue')
# Multiple selected items
await page.get_by_label('Choose multiple colors').select_option(['red', 'green', 'blue'])
鼠标点击
执行简单的模拟用户点击。
- 同步
- 异步
# Generic click
page.get_by_role("button").click()
# Double click
page.get_by_text("Item").dblclick()
# Right click
page.get_by_text("Item").click(button="right")
# Shift + click
page.get_by_text("Item").click(modifiers=["Shift"])
# Hover over element
page.get_by_text("Item").hover()
# Click the top left corner
page.get_by_text("Item").click(position={ "x": 0, "y": 0})
# Generic click
await page.get_by_role("button").click()
# Double click
await page.get_by_text("Item").dblclick()
# Right click
await page.get_by_text("Item").click(button="right")
# Shift + click
await page.get_by_text("Item").click(modifiers=["Shift"])
# Ctrl + click on Windows and Linux
# Meta + click on macOS
await page.get_by_text("Item").click(modifiers=["ControlOrMeta"])
# Hover over element
await page.get_by_text("Item").hover()
# Click the top left corner
await page.get_by_text("Item").click(position={ "x": 0, "y": 0})
在底层,此方法以及其他与指针相关的方法会:
- 等待具有给定选择器的元素出现在 DOM 中
- 等待它变为可见,即不为空,没有
display:none,没有visibility:hidden - 等待它停止移动,例如,直到 CSS 转换完成
- 将元素滚动到视图中
- 等待它在操作点接收指针事件,例如,等待直到元素不再被其他元素遮挡
- 如果在上述任何检查期间元素被分离,则重试
强制点击
有时,应用程序使用非标准的逻辑,其中悬停在元素上会用另一个元素覆盖它,从而拦截点击。这种行为与元素被覆盖且点击被分派到其他地方的错误无法区分。如果您知道这种情况正在发生,可以绕过 可操作性检查并强制点击
- 同步
- 异步
page.get_by_role("button").click(force=True)
await page.get_by_role("button").click(force=True)
程序化点击
如果您不关心在真实条件下测试您的应用程序,并且想用任何可能的方式模拟点击,您可以通过在元素上分派点击事件来触发 HTMLElement.click() 行为,方法是使用 locator.dispatch_event()
- 同步
- 异步
page.get_by_role("button").dispatch_event('click')
await page.get_by_role("button").dispatch_event('click')
输入字符
大多数情况下,您应该使用 locator.fill() 输入文本。请参阅上面的 文本输入 部分。只有当页面上有特殊的键盘处理时,您才需要输入字符。
使用 locator.press_sequentially() 逐个字符键入字段,就像使用真实键盘的用户一样。
- 同步
- 异步
# Press keys one by one
page.locator('#area').press_sequentially('Hello World!')
# Press keys one by one
await page.locator('#area').press_sequentially('Hello World!')
此方法将发出所有必要的键盘事件,包括 keydown、keyup、keypress 事件。您甚至可以指定按键之间的可选 delay 来模拟真实用户的行为。
按键和快捷键
- 同步
- 异步
# Hit Enter
page.get_by_text("Submit").press("Enter")
# Dispatch Control+Right
page.get_by_role("textbox").press("Control+ArrowRight")
# Press $ sign on keyboard
page.get_by_role("textbox").press("$")
# Hit Enter
await page.get_by_text("Submit").press("Enter")
# Dispatch Control+Right
await page.get_by_role("textbox").press("Control+ArrowRight")
# Press $ sign on keyboard
await page.get_by_role("textbox").press("$")
locator.press() 方法聚焦选定的元素并产生单个按键。它接受键盘事件中 keyboardEvent.key 属性发出的逻辑键名:keyboardEvent.key
Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape,
ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight,
ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc.
- 您也可以指定一个您想生成的单个字符,例如
"a"或"#"。 - 还支持以下修饰符快捷键:
Shift, Control, Alt, Meta。
简单版本生成单个字符。此字符区分大小写,因此 "a" 和 "A" 将产生不同的结果。
- 同步
- 异步
# <input id=name>
page.locator('#name').press('Shift+A')
# <input id=name>
page.locator('#name').press('Shift+ArrowLeft')
# <input id=name>
await page.locator('#name').press('Shift+A')
# <input id=name>
await page.locator('#name').press('Shift+ArrowLeft')
还支持 "Control+o" 或 "Control+Shift+T" 等快捷键。当与修饰符一起指定时,修饰符会被按下并保持,同时后续的键被按下。
请注意,您仍然需要在 Shift-A 中指定大写 A 才能生成大写字符。Shift-a 会生成小写字符,就像您切换了 CapsLock 一样。
上传文件
您可以使用 locator.set_input_files() 方法选择要上传的输入文件。它期望第一个参数指向一个类型为 "file" 的 input 元素。可以在数组中传递多个文件。如果某些文件路径是相对的,它们相对于当前工作目录解析。空数组会清除选定的文件。
- 同步
- 异步
# Select one file
page.get_by_label("Upload file").set_input_files('myfile.pdf')
# Select multiple files
page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
# Select a directory
page.get_by_label("Upload directory").set_input_files('mydir')
# Remove all the selected files
page.get_by_label("Upload file").set_input_files([])
# Upload buffer from memory
page.get_by_label("Upload file").set_input_files(
files=[
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
],
)
# Select one file
await page.get_by_label("Upload file").set_input_files('myfile.pdf')
# Select multiple files
await page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
# Select a directory
await page.get_by_label("Upload directory").set_input_files('mydir')
# Remove all the selected files
await page.get_by_label("Upload file").set_input_files([])
# Upload buffer from memory
await page.get_by_label("Upload file").set_input_files(
files=[
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
],
)
如果您没有获取到 input 元素(它是动态创建的),您可以处理 page.on("filechooser") 事件或在您的操作后使用相应的等待方法
- 同步
- 异步
with page.expect_file_chooser() as fc_info:
page.get_by_label("Upload file").click()
file_chooser = fc_info.value
file_chooser.set_files("myfile.pdf")
async with page.expect_file_chooser() as fc_info:
await page.get_by_label("Upload file").click()
file_chooser = await fc_info.value
await file_chooser.set_files("myfile.pdf")
聚焦元素
对于处理焦点事件的动态页面,您可以使用 locator.focus() 来聚焦给定的元素。
- 同步
- 异步
page.get_by_label('password').focus()
await page.get_by_label('password').focus()
拖放
您可以使用 locator.drag_to() 执行拖放操作。此方法将
- 悬停在将被拖动的元素上。
- 按下鼠标左键。
- 将鼠标移动到将接收拖放的元素上。
- 释放鼠标左键。
- 同步
- 异步
page.locator("#item-to-be-dragged").drag_to(page.locator("#item-to-drop-at"))
await page.locator("#item-to-be-dragged").drag_to(page.locator("#item-to-drop-at"))
手动拖动
如果您想要对拖动操作进行精确控制,请使用更底层的如 locator.hover(), mouse.down(), mouse.move() 和 mouse.up() 之类的方法。
- 同步
- 异步
page.locator("#item-to-be-dragged").hover()
page.mouse.down()
page.locator("#item-to-drop-at").hover()
page.mouse.up()
await page.locator("#item-to-be-dragged").hover()
await page.mouse.down()
await page.locator("#item-to-drop-at").hover()
await page.mouse.up()
如果您的页面依赖于分派 dragover 事件,则需要至少两次鼠标移动才能在所有浏览器中触发它。为了可靠地发出第二次鼠标移动,请将您的 mouse.move() 或 locator.hover() 重复两次。操作顺序应为:悬停在拖动元素上,鼠标按下,悬停在放置元素上,第二次悬停在放置元素上,鼠标抬起。
滚动
大多数情况下,Playwright 会在执行任何操作之前自动为您滚动。因此,您不需要显式滚动。
- 同步
- 异步
# Scrolls automatically so that button is visible
page.get_by_role("button").click()
# Scrolls automatically so that button is visible
await page.get_by_role("button").click()
但是,在极少数情况下,您可能需要手动滚动。例如,您可能希望强制“无限滚动”列表加载更多元素,或者为特定屏幕截图定位页面。在这种情况下,最可靠的方法是找到一个您希望使其在底部可见的元素,然后将其滚动到视图中。
- 同步
- 异步
# Scroll the footer into view, forcing an "infinite list" to load more content
page.get_by_text("Footer text").scroll_into_view_if_needed()
# Scroll the footer into view, forcing an "infinite list" to load more content
await page.get_by_text("Footer text").scroll_into_view_if_needed()
如果您想更精确地控制滚动,请使用 mouse.wheel() 或 locator.evaluate()
- 同步
- 异步
# Position the mouse and scroll with the mouse wheel
page.get_by_test_id("scrolling-container").hover()
page.mouse.wheel(0, 10)
# Alternatively, programmatically scroll a specific element
page.get_by_test_id("scrolling-container").evaluate("e => e.scrollTop += 100")
# Position the mouse and scroll with the mouse wheel
await page.get_by_test_id("scrolling-container").hover()
await page.mouse.wheel(0, 10)
# Alternatively, programmatically scroll a specific element
await page.get_by_test_id("scrolling-container").evaluate("e => e.scrollTop += 100")