playwright上传文件

针对系统中上传图片或者文件的功能,需要查看一下上传附件的元素是不是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,经验分享,python,playwright,自动化)