本文最后更新于:2023年1月17日 上午
                  
                
              
            
            
              
              首先,将下面html代码保存到一个文件中
后续第一种上传文件方式的代码小案例都是访问此html的
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">    <title>Title</title>
</head>
<body>
      <input type="file" name="pic" id="pic" />
</body>
</html>
比较简单,可以定位input标签后,直接 .send_keys() 就可以了
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | from selenium import webdriver
 driver = webdriver.Chrome("../resources/chromedriver.exe")
 
 driver.get("file:///C://上传文件.html")
 driver.maximize_window()
 
 pic = driver.find_element_by_id("pic")
 
 pic.send_keys(r"C:/上传文件.html")
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | from pathlib import Path
 # 打开上传网站
 driver.get("https://tinypng.com/")
 paths = Path.cwd().parent
 # 触发文件上传的操作
 driver.find_element_by_css_selector("section.target").click()
 time.sleep(2)
 # 一级顶层窗口
 dialog = win32gui.FindWindow("#32770", "打开")
 # 二级窗口
 comboBoxEx32 = win32gui.FindWindowEx(dialog, 0, "ComboBoxEx32", None)
 # 三级窗口
 comboBox = win32gui.FindWindowEx(comboBoxEx32, 0, "ComboBox", None)
 # 四级窗口 -- 文件路径输入区域
 edit = win32gui.FindWindowEx(comboBox, 0, "Edit", None)
 # 二级窗口 -- 打开按钮
 button = win32gui.FindWindowEx(dialog, 0, "Button", None)
 # 1、输入文件路径
 filepath = f"{paths}resources11.png"
 win32gui.SendMessage(edit, win32con.WM_SETTEXT, None, filepath)
 # 2、点击打开按钮
 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button)
 
 | 
这个是写死的方法,直接照搬即可,因为涉及了第三方工具去定位Window元素,暂时不展开详解
References