操作
簡介
Playwright 可以與 HTML 輸入元素互動,例如文字輸入框、核取方塊、選項按鈕、下拉式選單選項、滑鼠點擊、輸入字元、按鍵和快捷鍵,以及上傳檔案和聚焦元素。
文字輸入
使用 locator.fill() 是填寫表單欄位最簡單的方式。它會聚焦元素並觸發包含輸入文字的 input
事件。它適用於 <input>
、<textarea>
和 [contenteditable]
元素。
// Text input
await page.getByRole('textbox').fill('Peter');
// Date input
await page.getByLabel('Birth date').fill('2020-02-02');
// Time input
await page.getByLabel('Appointment time').fill('13:15');
// Local datetime input
await page.getByLabel('Local time').fill('2020-03-02T05:15');
核取方塊和選項按鈕
使用 locator.setChecked() 是選取和取消選取核取方塊或選項按鈕最簡單的方式。此方法可用於 input[type=checkbox]
、input[type=radio]
和 [role=checkbox]
元素。
// Check the checkbox
await page.getByLabel('I agree to the terms above').check();
// Assert the checked state
expect(page.getByLabel('Subscribe to newsletter')).toBeChecked();
// Select the radio button
await page.getByLabel('XL').check();
下拉式選單選項
使用 locator.selectOption() 在 <select>
元素中選取一個或多個選項。您可以指定選項的 value
或 label
來選取。可以選取多個選項。
// Single selection matching the value or label
await page.getByLabel('Choose a color').selectOption('blue');
// Single selection matching the label
await page.getByLabel('Choose a color').selectOption({ label: 'Blue' });
// Multiple selected items
await page.getByLabel('Choose multiple colors').selectOption(['red', 'green', 'blue']);
滑鼠點擊
執行簡單的人工點擊。
// Generic click
await page.getByRole('button').click();
// Double click
await page.getByText('Item').dblclick();
// Right click
await page.getByText('Item').click({ button: 'right' });
// Shift + click
await page.getByText('Item').click({ modifiers: ['Shift'] });
// Ctrl + click on Windows and Linux
// Meta + click on macOS
await page.getByText('Item').click({ modifiers: ['ControlOrMeta'] });
// Hover over element
await page.getByText('Item').hover();
// Click the top left corner
await page.getByText('Item').click({ position: { x: 0, y: 0 } });
在底層,此方法和其他指標相關方法
- 等待具有給定選擇器的元素出現在 DOM 中
- 等待它變成顯示狀態,即非空、沒有
display:none
、沒有visibility:hidden
- 等待它停止移動,例如,直到 CSS 轉換完成
- 將元素滾動到檢視範圍內
- 等待它在動作點接收指標事件,例如,等待直到元素不被其他元素遮蔽
- 如果在上述任何檢查期間元素分離,則重試
強制點擊
有時,應用程式會使用非顯而易見的邏輯,其中懸停元素會以另一個攔截點擊的元素覆蓋它。這種行為與元素被覆蓋且點擊被發送到其他位置的錯誤無法區分。如果您知道這種情況正在發生,您可以繞過 可操作性 檢查並強制點擊
await page.getByRole('button').click({ force: true });
程式化點擊
如果您對在真實條件下測試您的應用程式不感興趣,並且想要以任何可能的方式模擬點擊,您可以透過簡單地使用 locator.dispatchEvent() 在元素上派發點擊事件來觸發 HTMLElement.click()
行為
await page.getByRole('button').dispatchEvent('click');
輸入字元
大多數時候,您應該使用 locator.fill() 輸入文字。請參閱上面的文字輸入章節。只有在頁面上存在特殊的鍵盤處理時,您才需要輸入字元。
使用 locator.pressSequentially() 逐個字元地輸入到欄位中,就像使用者使用真實鍵盤一樣。
// Press keys one by one
await page.locator('#area').pressSequentially('Hello World!');
此方法將發出所有必要的鍵盤事件,並包含所有 keydown
、keyup
、keypress
事件。您甚至可以指定按鍵之間的選用 delay
來模擬真實使用者行為。
按鍵和快捷鍵
// Hit Enter
await page.getByText('Submit').press('Enter');
// Dispatch Control+Right
await page.getByRole('textbox').press('Control+ArrowRight');
// Press $ sign on keyboard
await page.getByRole('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>
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.setInputFiles() 方法選取要上傳的輸入檔案。它期望第一個引數指向類型為 "file"
的 input 元素。可以在陣列中傳遞多個檔案。如果某些檔案路徑是相對的,則它們會相對於目前的工作目錄解析。空陣列會清除選定的檔案。
// Select one file
await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));
// Select multiple files
await page.getByLabel('Upload files').setInputFiles([
path.join(__dirname, 'file1.txt'),
path.join(__dirname, 'file2.txt'),
]);
// Select a directory
await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir'));
// Remove all the selected files
await page.getByLabel('Upload file').setInputFiles([]);
// Upload buffer from memory
await page.getByLabel('Upload file').setInputFiles({
name: 'file.txt',
mimeType: 'text/plain',
buffer: Buffer.from('this is test')
});
如果您手邊沒有輸入元素(它是動態建立的),您可以處理 page.on('filechooser') 事件,或在您的操作時使用相應的等待方法
// Start waiting for file chooser before clicking. Note no await.
const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByLabel('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));
聚焦元素
對於處理焦點事件的動態頁面,您可以使用 locator.focus() 聚焦給定的元素。
await page.getByLabel('Password').focus();
拖放
您可以使用 locator.dragTo() 執行拖放操作。此方法將會
- 懸停將被拖曳的元素。
- 按下滑鼠左鍵。
- 將滑鼠移動到將接收放置的元素。
- 釋放滑鼠左鍵。
await page.locator('#item-to-be-dragged').dragTo(page.locator('#item-to-drop-at'));
手動拖曳
如果您想要精確控制拖曳操作,請使用較低層級的方法,例如 locator.hover()、mouse.down()、mouse.move() 和 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
await page.getByRole('button').click();
但是,在極少數情況下,您可能需要手動滾動。例如,您可能想要強制「無限列表」載入更多元素,或將頁面定位到特定螢幕截圖的位置。在這種情況下,最可靠的方法是找到您想要在底部顯示的元素,並將其滾動到檢視範圍內。
// Scroll the footer into view, forcing an "infinite list" to load more content
await page.getByText('Footer text').scrollIntoViewIfNeeded();
如果您想要更精確地控制滾動,請使用 mouse.wheel() 或 locator.evaluate()
// Position the mouse and scroll with the mouse wheel
await page.getByTestId('scrolling-container').hover();
await page.mouse.wheel(0, 10);
// Alternatively, programmatically scroll a specific element
await page.getByTestId('scrolling-container').evaluate(e => e.scrollTop += 100);