FileChooser对象通过page.on("filechoose")事件监听。
如下代码实现点击百度搜图按钮,上传文件进行搜索。
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False,slow_mo=1000)
context = browser.new_context()
page=context.new_page()
page.goto("https://www.baidu.com/")
page.locator("span").filter(has_text="按图片搜索").locator("span").first.click()
# page.locator("input[type=\"file\"]").set_input_files("2.png")
with page.expect_file_chooser() as fc_info:
page.locator("input[type=\"file\"]").click()
file_chooser = fc_info.value
file_chooser.set_files(r"C:\Users\Administrator\Desktop\2.png")
page.pause()
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
方法
set_files
为文件选择器设置要上传的文件路径
file_chooser.set_files(files)
file_chooser.set_files(files, **kwargs)
属性
element
返回文件选择器关联的input元素
file_chooser.element
is_multiple
返回文件选择器是否接收多个文件
file_chooser.is_multiple()
page
返回文件选择器所属页面。
file_chooser.page