针对系统中上传图片或者文件的功能,需要查看一下上传附件的元素是不是file类型的input标签
file类型input标签上传附件
- 第一步:定位input标签
- 第二步:上传文件
- 上传多个文件,则set_input_files传一个file的list即可
# 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_chooser.is_multiple(): 返回值是true 或者false, 控件是否支持上传多个文件
- file_chooser.element: 返回上传附件的元素对象elementhandle
- file_chooser.page: 返回file_chooser所属的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上传文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论