方法一
如果有上传图片按钮的,就比较简单了:
browser.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")
browser.find_element_by_xpath("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")
但如果需要手动点一下再选择图片的,就没法这样了。
方法二
使用autoit这个软件来实现。然后生成exe,使用Python来调用它。但这样比较麻烦,需要写死文件。
WinWait("File Upload", "", 5000);
WinActivate("File Upload");
ControlFocus("File Upload","","Edit1")
Sleep(1000);
WinWait("[CLASS:#32770]","",100) ;绛夊緟0.1绉?
ControlSetText("File Upload", "", "Edit1", "C:\Users\SXF\Desktop\Python\doubanReg\Post_Up_2\Reply\essay\绐濊叮鏄搨娑涢泦鍥㈡棗涓嬪搧鐗屽叕瀵擄紝鎻愪緵鑸掗€傝叮鍛崇殑鐢熸椿浣撻獙") ;鎵撳紑鏂囦欢鐩綍
Sleep(1000);
ControlClick("File Upload", "", "Button1");
Sleep(1000);
WinWait("[CLASS:#32770]","",100) ;绛夊緟0.1绉?
ControlSetText("File Upload", "", "Edit1", '"1.png" "2.png" "3.png" "4.png" "5.png"');
Sleep(1000);
ControlClick("File Upload", "", "Button1");
Sleep(5000);
方法三
使用Python的autoit库来完成!语法跟软件一模一样!
import autoit
autoit.win_active("Open")
autoit.control_send("Open","Edit1",r"C:\Users\uu\Desktop\TestUpload.txt")
autoit.control_send("Open","Edit1","{ENTER}")
# 建议使用control_set_text 因为control_send会发送错误的文本
autoit.control_set_text("Open","Edit1",r"C:\Users\uu\Desktop\TestUpload.txt")
或
import autoit
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
ActionChains(driver).move_to_element( driver.find_element_by_xpath("//path/to/upload/button")).click().perform()
handle = "[CLASS:#32770; TITLE:Open]"
autoit.win_wait(handle, 60)
autoit.control_set_text(handle, "Edit1", "\\file\\path")
autoit.control_click(handle, "Button1")
但注意,程序在运行时候,不能有人为干扰!
如果打包时候出错,请看这个:
解决方案 Autoit Pyinstaller OSError: Cannot load AutoItX from path