操作
文本输入
使用 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 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 过渡完成
-
将元素滚动到视图中
-
等待元素在操作点接收指针事件,例如等待元素不被其他元素遮挡
-
如果元素在上述检查过程中被分离,重试
输入字符
大多数情况下,你应该使用 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"
的快捷键。当指定修饰符时,修饰符会被按下并保持,而随后的键会被按下。
注意:你仍然需要指定大写字母 "A"
来产生大写字符。Shift-a
会生成小写字母,就像 CapsLock
被切换一样。
上传文件
你可以使用 locator.setInputFiles() 方法选择上传的输入文件。它期望第一个参数指向类型为 file
的输入元素。可以传递多个文件,文件路径如果是相对路径,会相对于当前工作目录解析。空数组会清除已选择的文件。
// 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.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();
如果你的页面依赖于 |
滚动
大多数情况下,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);