跳到主要內容

操作

簡介

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 過渡效果完成
  • 滾動元素到可視範圍內
  • 等待它在操作點接收指標事件,例如,等待元素不被其他元素遮蔽
  • 如果在上述任何檢查期間元素被分離,則重試

強制點擊

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

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

程式化點擊

如果您對在真實條件下測試您的應用程式不感興趣,並且想以任何可能的方式模擬點擊,您可以通過使用 locator.dispatch_event() 在元素上簡單地派發一個 click 事件來觸發 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 事件。您甚至可以指定按鍵之間的延遲時間,以模擬真實使用者行為。

按鍵和快捷鍵

# 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""#"
  • 也支援以下修改快捷鍵: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.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"}
],
)

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