操作
簡介
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();
選擇選項
選擇 <select>
元素中的一個或多個選項,使用 locator.selectOption()。您可以指定選項的 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 or 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 過渡完成
- 滾動元素進入視圖
- 等待它在動作點接收指標事件,例如,等待元素不再被其他元素遮擋
- 如果元素在上述任何檢查期間被分離,則重試
強制點擊
有時,應用程式會使用複雜的邏輯,其中懸停在元素上會覆蓋另一個攔截點擊的元素。這種行為與元素被覆蓋且點擊被分派到其他地方的錯誤無法區分。如果你知道這種情況正在發生,你可以繞過actionability檢查並強制點擊:
await page.getByRole('button').click({ force: true });
程式碼點擊
如果你不想在真實條件下測試你的應用程式,並且想盡可能模擬點擊,你可以通過在元素上簡單地分派一個點擊事件來觸發 HTMLElement.click()
行為,使用 locator.dispatchEvent():
await page.getByRole('button').dispatchEvent('click');
鍵入字元
大多數情況下,你應該使用 locator.fill() 輸入文字。請參閱上面的 Text input 部分。只有在頁面上有特殊鍵盤處理時,你才需要輸入字元。
逐字輸入到欄位中,就像使用真實鍵盤的使用者一樣,使用 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"
也受到支援。當指定了修飾鍵時,修飾鍵會被按下並保持,同時按下後續的鍵。
請注意,你仍然需要指定大寫的 A
在 Shift-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);