python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > playwright上传文件

playwright上传文件的实现示例

作者:z917185537

本文主要介绍了playwright上传文件的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

针对系统中上传图片或者文件的功能,需要查看一下上传附件的元素是不是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上传文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文