动作
介绍
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 过渡效果结束
- 将元素滚动到可见区域
- 等待其在操作点接收指针事件,例如,等待元素不再被其他元素遮挡
- 如果元素在上述任何检查过程中被分离,则重试
强制点击
有时,应用程序使用非简单逻辑,悬停元素时会叠加另一个元素拦截点击。这种行为与元素被覆盖导致点击被分派到其他位置的 bug 无法区分。如果您知道正在发生这种情况,可以绕过可操作性检查并强制点击。
- 同步
- 异步
page.get_by_role("button").click(force=True)
await page.get_by_role("button").click(force=True)
编程点击
如果您不关心在真实条件下测试您的应用程序,并且希望通过任何可能的方式模拟点击,您可以通过使用 locator.dispatch_event() 在元素上分派一个点击事件来触发 HTMLElement.click()
行为。
- 同步
- 异步
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 属性中发出的逻辑按键名称
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"}
],
)
如果您没有现成的输入元素(它是动态创建的),您可以处理 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")