开发者

python+playwright 元素操作示例代码

目录
  • fill() 输入文字
  • 同步示例
  • 异步示例
  • 鼠标点击 click()
  • 文件上传
  • select 下拉框
  • 复选框和单选
  • focus()聚焦给定元素
  • drag_to 拖动元素

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 pag编程客栈e.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")
# Shipythonft + 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").clicphpk(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": android"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"))

到此这篇关于python+playwright 元素操作的文章就介绍到这了,更多相关python playwright 元素内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜