python+playwright 元素操作

Playwright 可以与 HTML 输入元素交互,例如文本输入、复选框、单选按钮、选择选项、鼠标单击、键入字符、键和快捷方式以及上传文件和焦点元素。

fill() 输入文字

使用 locator.fill() 是填写表单字段的最简单方法。它聚焦元素并input使用输入的文本触发事件。它适用于<input>,<textarea>[contenteditable]元素。

同步示例

# Text 文本框输入
page.get_by_role("textbox").fill("Peter")

# 根据label 定位 Date 日期输入
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")

异步示例

# Text input
await page.get_by_role("textbox").fill("Peter")

# Date input
await page.get_by_label("Birth date").fill("2020-02-02")

# Time input
await page.get_by_label("Appointment time").fill("13:15")

# Local datetime input
await page.get_by_label("Local time").fill("2020-03-02T05:15")

鼠标点击 click()

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

文件上传

可以使用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'])

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

select 下拉框

# Single selection matching the value
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'])

复选框和单选

# Check the checkbox
page.get_by_label('I agree to the terms above').check()

# Assert the checked state
assert page.get_by_label('Subscribe to newsletter').is_checked() is True

# Select the radio button
page.get_by_label('XL').check()

focus()聚焦给定元素

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

drag_to 拖动元素

此方法将:

  • 将鼠标悬停在要拖动的元素上。
  • 按鼠标左键。
  • 将鼠标移动到将接收放置的元素。
  • 松开鼠标左键。
page.locator("#item-to-be-dragged").drag_to(page.locator("#item-to-drop-at"))

 

posted @ 2023-10-07 15:49  keena_jiao  阅读(157)  评论(0编辑  收藏  举报