it编程 > 编程语言 > 其他编程

playwright上传文件的实现示例

25人参与 2026-01-25 其他编程

针对系统中上传图片或者文件的功能,需要查看一下上传附件的元素是不是file类型的input标签

file类型input标签上传附件

# select one file
page.locator("input_file").set_input_files('myfile.pdf')
# select multiple files
page.locator("input_file").set_input_files(['file1.txt', 'file2.txt'])
# remove all the selected files
page.locator("input_file").set_input_files([])

非input标签,filechooser实现方法

filechooser对象实现,如下所示

with self.page.expect_file_chooser() as fc_info:
     self.page.get_by_role("button", name="picture").click() # 点击上传附件按钮
file_chooser = fc_info.value
file_chooser.set_files(get_path(f"{file}")) # 上传文件 ,或者上传多个文件file_chooser.set_files(['file1.txt', 'file2.txt'])

filechooser对象

filechooser对象除了set_files方法,还有is_multiple,element,page

⚠️需要注意上传文件的路径,可以放在统一位置,比如统一放在file文件夹下,写一个通用的获取文件路径的方法, 就可以通过get_path(file_name)获取文件

def get_path(name):
    current_path = os.path.dirname(os.path.dirname(__file__))  # utils dir
    root_dir = os.path.abspath(current_path)  # the parent dir of utils
    file = os.path.join(root_dir, "file", name)
    return file

到此这篇关于playwright上传文件的实现示例的文章就介绍到这了,更多相关playwright上传文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

playwright保持网站的登录状态的几种方法

01-25

playwright日期控件的具体使用

01-25

PlayWright 元素拖动的实现示例

01-25

VSCode设置Playwright的图文教程

01-25

Git开发分支合并到develop分支实现方式

01-23

Git中忽略文件机制的.gitignore与.git/info/exclude两种方式详解

01-26

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论