Actions
簡介
Playwright 可以與 HTML 輸入元素互動,包括文字輸入、核取方塊、單選按鈕、選擇選項、滑鼠點擊、輸入字元、按鍵和快捷鍵,以及上傳檔案和聚焦元素。
文字輸入
使用 Locator.fill()
是填寫表單欄位最簡單的方式。它會聚焦元素並觸發包含輸入文字的 input
事件。適用於 <input>
、<textarea>
和 [contenteditable]
元素。
// Text input
page.getByRole(AriaRole.TEXTBOX).fill("Peter");
// Date input
page.getByLabel("Birth date").fill("2020-02-02");
// Time input
page.getByLabel("Appointment time").fill("13-15");
// Local datetime input
page.getByLabel("Local time").fill("2020-03-02T05:15");
核取方塊和單選按鈕
使用 Locator.setChecked()
是勾選和取消勾選核取方塊或單選按鈕最簡單的方式。此方法適用於 input[type=checkbox]
、input[type=radio]
和 [role=checkbox]
元素。
// Check the checkbox
page.getByLabel("I agree to the terms above").check();
// Assert the checked state
assertTrue(page.getByLabel("Subscribe to newsletter")).isChecked();
// Select the radio button
page.getByLabel("XL").check();
選擇選項
使用 Locator.selectOption()
在 <select>
元素中選擇一個或多個選項。您可以指定選項的 value
或 label
來選擇。可以選擇多個選項。
// Single selection matching the value or label
page.getByLabel("Choose a color").selectOption("blue");
// Single selection matching the label
page.getByLabel("Choose a color").selectOption(new SelectOption().setLabel("Blue"));
// Multiple selected items
page.getByLabel("Choose multiple colors").selectOption(new String[] {"red", "green", "blue"});
滑鼠點擊
執行簡單的人為點擊操作。
// Generic click
page.getByRole(AriaRole.BUTTON).click();
// Double click
page.getByText("Item").dblclick();
// Right click
page.getByText("Item").click(new Locator.ClickOptions().setButton(MouseButton.RIGHT));
// Shift + click
page.getByText("Item").click(new Locator.ClickOptions().setModifiers(Arrays.asList(KeyboardModifier.SHIFT)));
// Ctrl + click on Windows and Linux
// Meta + click on macOS
page.getByText("Item").click(new Locator.ClickOptions().setModifiers(Arrays.asList(KeyboardModifier.CONTROL_OR_META)));
// Hover over element
page.getByText("Item").hover();
// Click the top left corner
page.getByText("Item").click(new Locator.ClickOptions().setPosition(0, 0));
在底層,這個方法以及其他指標相關方法會:
- 等待具有指定選擇器的元素出現在 DOM 中
- 等待元素變為可顯示狀態,即不為空、沒有
display:none
、沒有visibility:hidden
- 等待元素停止移動,例如等待 CSS 轉場效果完成
- 將元素滾動到視圖中
- 等待元素在操作點接收指標事件,例如等待元素不被其他元素遮蔽
- 如果在上述任何檢查過程中元素被分離,則重試
強制點擊
有時,應用程式使用非平凡的邏輯,其中懸停元素會用另一個攔截點擊的元素覆蓋它。這種行為與元素被覆蓋且點擊被分派到其他地方的錯誤無法區分。如果您知道正在發生這種情況,可以繞過可操作性檢查並強制點擊:
page.getByRole(AriaRole.BUTTON).click(new Locator.ClickOptions().setForce(true));
程式化點擊
如果您不想在真實條件下測試應用程式,而想要以任何可能的方式模擬點擊,可以透過使用 Locator.dispatchEvent()
在元素上簡單地分派點擊事件來觸發 HTMLElement.click()
行為:
page.getByRole(AriaRole.BUTTON).dispatchEvent("click");
輸入字元
大多數情況下,您應該使用 Locator.fill()
來輸入文字。請參閱上面的文字輸入部分。只有當頁面上有特殊的鍵盤處理時,才需要輸入字元。
使用 Locator.pressSequentially()
逐個字元地輸入到欄位中,就像使用真實鍵盤的使用者一樣。
// Press keys one by one
page.locator("#area").pressSequentially("Hello World!");
此方法會發出所有必要的鍵盤事件,包括所有的 keydown
、keyup
、keypress
事件。您甚至可以指定按鍵之間的可選 delay
來模擬真實使用者行為。
按鍵和快捷鍵
// Hit Enter
page.getByText("Submit").press("Enter");
// Dispatch Control+Right
page.getByRole(AriaRole.TEXTBOX).press("Control+ArrowRight");
// Press $ sign on keyboard
page.getByRole(AriaRole.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");
也支援 "Control+o"
或 "Control+Shift+T"
等快捷鍵。當與修飾鍵一起指定時,修飾鍵會被按下並保持,而後續的按鍵被按下。
請注意,您仍然需要在 Shift-A
中指定大寫 A
才能產生大寫字元。Shift-a
會產生小寫字元,就像您切換了 CapsLock
一樣。
上傳檔案
您可以使用 Locator.setInputFiles()
方法選擇要上傳的輸入檔案。它期望第一個參數指向類型為 "file"
的輸入元素。可以在陣列中傳遞多個檔案。如果某些檔案路徑是相對的,它們會相對於當前工作目錄解析。空陣列會清除選定的檔案。
// Select one file
page.getByLabel("Upload file").setInputFiles(Paths.get("myfile.pdf"));
// Select multiple files
page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
// Select a directory
page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
// Remove all the selected files
page.getByLabel("Upload file").setInputFiles(new Path[0]);
// Upload buffer from memory
page.getByLabel("Upload file").setInputFiles(new FilePayload(
"file.txt", "text/plain", "this is test".getBytes(StandardCharsets.UTF_8)));
如果您手邊沒有輸入元素(它是動態建立的),您可以處理 Page.onFileChooser(handler)
事件或在您的操作中使用對應的等待方法:
FileChooser fileChooser = page.waitForFileChooser(() -> {
page.getByLabel("Upload file").click();
});
fileChooser.setFiles(Paths.get("myfile.pdf"));
聚焦元素
對於處理聚焦事件的動態頁面,您可以使用 Locator.focus()
聚焦指定的元素。
page.getByLabel("Password").focus();
拖放
您可以使用 Locator.dragTo()
執行拖放操作。此方法會:
- 懸停要拖動的元素。
- 按下滑鼠左鍵。
- 將滑鼠移動到將接收放置的元素。
- 釋放滑鼠左鍵。
page.locator("#item-to-be-dragged").dragTo(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();
如果您的頁面依賴於分派 dragover
事件,您需要至少兩次滑鼠移動才能在所有瀏覽器中觸發它。要可靠地發出第二次滑鼠移動,請重複您的 Mouse.move()
或 Locator.hover()
兩次。操作序列應為:懸停拖動元素、滑鼠按下、懸停放置元素、第二次懸停放置元素、滑鼠釋放。
滾動
大多數情況下,Playwright 會在執行任何操作之前自動為您滾動。因此,您不需要明確地滾動。
// Scrolls automatically so that button is visible
page.getByRole(AriaRole.BUTTON).click();
然而,在極少數情況下,您可能需要手動滾動。例如,您可能想要強制「無限清單」載入更多元素,或者為特定螢幕截圖定位頁面。在這種情況下,最可靠的方法是找到您想要在底部顯示的元素,並將其滾動到視圖中。
// Scroll the footer into view, forcing an "infinite list" to load more content
page.getByText("Footer text").scrollIntoViewIfNeeded();
如果您想要更精確地控制滾動,請使用 Mouse.wheel()
或 Locator.evaluate()
:
// Position the mouse and scroll with the mouse wheel
page.getByTestId("scrolling-container").hover();
page.mouse.wheel(0, 10);
// Alternatively, programmatically scroll a specific element
page.getByTestId("scrolling-container").evaluate("e => e.scrollTop += 100");