Actions
簡介
Playwright 可以與 HTML 輸入元素互動,包括文字輸入、核取方塊、單選按鈕、選擇選項、滑鼠點擊、輸入字元、按鍵和快捷鍵,以及上傳檔案和聚焦元素。
文字輸入
使用 locator.fill()
是填寫表單欄位最簡單的方式。它會聚焦元素並觸發包含輸入文字的 input
事件。適用於 <input>
、<textarea>
和 [contenteditable]
元素。
- Sync
- Async
# 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]
元素。
- Sync
- Async
# 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
來選擇。可以選擇多個選項。
- Sync
- Async
# 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'])
滑鼠點擊
執行簡單的人為點擊操作。
- Sync
- Async
# 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 轉場效果完成
- 將元素滾動到視圖中
- 等待元素在操作點接收指標事件,例如等待元素不被其他元素遮蔽
- 如果在上述任何檢查過程中元素被分離,則重試
強制點擊
有時,應用程式使用非平凡的邏輯,其中懸停元素會用另一個攔截點擊的元素覆蓋它。這種行為與元素被覆蓋且點擊被分派到其他地方的錯誤無法區分。如果您知道正在發生這種情況,可以繞過可操作性檢查並強制點擊:
- Sync
- Async
page.get_by_role("button").click(force=True)
await page.get_by_role("button").click(force=True)
程式化點擊
如果您不想在真實條件下測試應用程式,而想要以任何可能的方式模擬點擊,可以透過使用 locator.dispatch_event()
在元素上簡單地分派點擊事件來觸發 HTMLElement.click()
行為:
- Sync
- Async
page.get_by_role("button").dispatch_event('click')
await page.get_by_role("button").dispatch_event('click')
輸入字元
大多數情況下,您應該使用 locator.fill()
來輸入文字。請參閱上面的文字輸入部分。只有當頁面上有特殊的鍵盤處理時,才需要輸入字元。
使用 locator.press_sequentially()
逐個字元地輸入到欄位中,就像使用真實鍵盤的使用者一樣。
- Sync
- Async
# 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
來模擬真實使用者行為。
按鍵和快捷鍵
- Sync
- Async
# 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"
會產生不同的結果。
- Sync
- Async
# <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"
的輸入元素。可以在陣列中傳遞多個檔案。如果某些檔案路徑是相對的,它們會相對於當前工作目錄解析。空陣列會清除選定的檔案。
- Sync
- Async
# 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")
事件或在您的操作中使用對應的等待方法:
- Sync
- Async
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()
聚焦指定的元素。
- Sync
- Async
page.get_by_label('password').focus()
await page.get_by_label('password').focus()
拖放
您可以使用 locator.drag_to()
執行拖放操作。此方法會:
- 懸停要拖動的元素。
- 按下滑鼠左鍵。
- 將滑鼠移動到將接收放置的元素。
- 釋放滑鼠左鍵。
- Sync
- Async
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()
。
- Sync
- Async
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 會在執行任何操作之前自動為您滾動。因此,您不需要明確地滾動。
- Sync
- Async
# 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()
然而,在極少數情況下,您可能需要手動滾動。例如,您可能想要強制「無限清單」載入更多元素,或者為特定螢幕截圖定位頁面。在這種情況下,最可靠的方法是找到您想要在底部顯示的元素,並將其滾動到視圖中。
- Sync
- Async
# 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()
:
- Sync
- Async
# 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")