跳到主要內容

操作

簡介

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")

複選框和單選按鈕

使用 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()

選擇選項

使用 locator.select_option()<select> 元素中選取一個或多個選項。您可以指定選項的 valuelabel 來選取。可以選取多個選項。

# 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'])

滑鼠點擊

執行簡單的人工點擊。

# 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})

在底層,此方法和其他指標相關的方法

  • 等待具有給定選擇器的元素出現在 DOM 中
  • 等待它變成顯示狀態,即非空、沒有 display:none、沒有 visibility:hidden
  • 等待它停止移動,例如,直到 CSS 過渡完成
  • 將元素滾動到視野中
  • 等待它在動作點接收指標事件,例如,等待直到元素不被其他元素遮蔽
  • 如果在上述任何檢查期間元素被分離,則重試

強制點擊

有時,應用程式會使用非平凡的邏輯,其中懸停元素會用另一個元素覆蓋它,從而攔截點擊。這種行為與元素被覆蓋且點擊被發送到其他地方的錯誤難以區分。如果您知道這種情況正在發生,您可以繞過 可操作性 檢查並強制點擊

page.get_by_role("button").click(force=True)

程式化點擊

如果您對在真實條件下測試您的應用程式不感興趣,並且想要以任何可能的方式模擬點擊,您可以透過使用 locator.dispatch_event() 在元素上簡單地發送點擊事件來觸發 HTMLElement.click() 行為

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!')

此方法將發出所有必要的鍵盤事件,並包含所有 keydownkeyupkeypress 事件。您甚至可以指定按鍵之間的可選 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("$")

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""#"
  • 也支援以下修改快捷鍵:ShiftControlAltMeta

簡單版本產生單個字元。此字元區分大小寫,因此 "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.set_input_files() 方法選擇要上傳的輸入檔案。它預期第一個參數指向類型為 "file"輸入元素。可以在陣列中傳遞多個檔案。如果某些檔案路徑是相對路徑,則它們會相對於當前工作目錄解析。空陣列會清除選定的檔案。

# 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"}
],
)

如果您手邊沒有輸入元素(它是動態建立的),您可以處理 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")

聚焦元素

對於處理焦點事件的動態頁面,您可以使用 locator.focus() 聚焦給定的元素。

page.get_by_label('password').focus()

拖放

您可以使用 locator.drag_to() 執行拖放操作。此方法將會

  • 懸停將被拖曳的元素。
  • 按下滑鼠左鍵。
  • 將滑鼠移動到將接收放置的元素。
  • 釋放滑鼠左鍵。
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()
注意

如果您的頁面依賴於發送 dragover 事件,則您至少需要兩次滑鼠移動才能在所有瀏覽器中觸發它。為了可靠地發出第二次滑鼠移動,請重複您的 mouse.move()locator.hover() 兩次。操作順序將是:懸停拖曳元素、按下滑鼠按鈕、懸停放置元素、第二次懸停放置元素、鬆開滑鼠按鈕。

滾動

大多數時候,Playwright 會在執行任何操作之前自動為您滾動。因此,您不需要明確地滾動。

# Scrolls automatically so that button is visible
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()

如果您想要更精確地控制滾動,請使用 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")