用python写个selenium上传文件的程序,非input标签的上传
非input标签的上传通常是通过模拟点击“上传”按钮打开系统的文件选择框,然后在文件选择框中选择文件并点击“确定”按钮实现的。在Selenium中,我们可以使用AutoIT或pywinauto等工具来模拟操作系统的窗口,实现非input标签的上传。
下面是一个使用pywinauto模块实现非input标签上传文件的示例程序:
from selenium import webdriver from pywinauto.application import Application from pywinauto.keyboard import send_keys # 指定要上传的文件路径 file_path = r"C:\path\to\your\file.jpg" # 创建WebDriver对象,这里使用Chrome浏览器作为示例 driver = webdriver.Chrome() # 打开要上传文件的页面 driver.get("https://example.com/upload") # 找到上传按钮并点击 upload_button = driver.find_element_by_xpath("//button[@class='upload-button']") upload_button.click() # 使用pywinauto模块模拟系统的文件选择框 app = Application(backend='uia').connect(title='打开') # 打开系统的文件选择框 app['打开']['文件名(N):Edit'].set_text(file_path) # 将要上传的文件路径填入文件名输入框 send_keys("{ENTER}") # 模拟按下回车键,选择文件并点击“确定”按钮 # 等待上传完成 # ... # 关闭浏览器 driver.quit()
在这个示例中,我们使用了pywinauto模块模拟了系统的文件选择框,找到了文件名输入框并将要上传的文件的路径填入该输入框,然后模拟按下回车键,选择文件并点击“确定”按钮完成文件的选择。请注意,要将C:\path\to\your\file.jpg替换为实际要上传的文件的路径。
上传完成后,您可以使用Selenium的等待功能等待页面中上传成功的提示信息出现,然后关闭浏览器
新实例:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from pywinauto.application import Application from pywinauto.keyboard import send_keys import time # 指定要上传的文件路径 file_path = r"C:\Users\Administrator\Desktop\1\f69e1dd88b3e90726e4d6cee1baa709.jpg" # 创建WebDriver对象,这里使用Chrome浏览器作为示例 driver = webdriver.Chrome() # 打开要上传文件的页面 driver.get("https://layuion.com/docs/modules/upload.html") # 等待上传按钮出现并点击 upload_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "test1")) ) upload_button.click() time.sleep(3) # 使用pywinauto模块模拟系统的文件选择框 app = Application().connect(path="C:\Program Files\Google\Chrome\Application\chrome.exe") # 打开系统的文件选择框 send_keys(file_path)# 将要上传的文件路径填入文件名输入框 time.sleep(3) send_keys("{ENTER}") # 模拟按下回车键,选择文件并点击“确定”按钮 # 等待上传完成 # ... input('ok?') # 关闭浏览器 driver.quit()