使用Python与Selenium实现文件上传自动化遇阻求助
问题描述
我正尝试使用Python和Selenium自动化一项任务,对两者都非常陌生,缺乏相关经验。任务中有一个环节需要访问网页上传本地文件资源管理器中的文件,查阅相关资料但始终无法成功。以下是我的实现代码:
from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select from selenium.webdriver.support import expected_conditions as EC #this is used to not let chrome close options = webdriver.ChromeOptions() options.add_experimental_option("detach", True) driver=webdriver.Chrome(options=options,service=ChromeService(ChromeDriverManager().install())) driver.maximize_window() driver.get("url") #to be able to click button button1 = driver.find_element(By.CLASS_NAME,"button1") button1.click() #sign into to website username = driver.find_element(By.NAME, "UserName") username.send_keys('username') password = driver.find_element(By.NAME, "Password") password.send_keys('password') form = driver.find_element(By.ID, "submitButton") form.submit() #MFA button2 = driver.find_element(By.ID, "button2") button2.click() WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='duo_iframe']"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Send Me a Push']"))).click() #website and choosing drop-down WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "ID"))).click() dd = Select(driver.find_element(By.ID, "id")) dd.select_by_value("value") #click the upload button and file explorer window opens button3 = driver.find_element(By.ID, "button3") button3.click() element = driver.find_element(By.CLASS_NAME, "class_name") driver.execute_script("arguments[0].click();", element) #selecting the file to upload into website - stuck here print("Application title is ",driver.title) print("Application url is ",driver.current_url)
目前卡在点击上传按钮弹出文件资源管理器后,无法自动选择文件完成上传的步骤,恳请提供解决方案。
解决方案
- 核心逻辑:Selenium无法直接操控系统级的文件资源管理器窗口,正确的做法是定位页面中负责文件上传的
<input type="file">元素,直接通过send_keys()方法传入本地文件的绝对路径。 - 具体操作步骤:
- 找到页面里的文件上传输入框(通常是
<input>标签,type属性为file),可通过By.CSS_SELECTOR、By.XPATH等方式定位。 - 无需触发上传按钮弹出系统对话框,直接对该
<input>元素调用send_keys(),传入文件的完整路径。
- 找到页面里的文件上传输入框(通常是
- 替换你卡住部分的代码示例:
# 等待并定位文件上传的input元素(需根据实际页面调整定位表达式) upload_input = WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")) ) # 传入本地文件的绝对路径,Windows系统注意用/或转义的\\ upload_input.send_keys("C:/Users/你的用户名/文档/test_file.pdf") # 如果页面需要点击确认上传的按钮,再定位并点击 # confirm_btn = driver.find_element(By.ID, "confirm_upload_btn") # confirm_btn.click()
- 注意事项:
- 若
<input type="file">元素被隐藏,可先用execute_script()使其可见,再执行send_keys()。 - 必须使用文件的绝对路径,避免因相对路径导致的找不到文件问题。
- 若
内容的提问来源于stack exchange,提问作者Zyngle
相关产品推荐
相关产品推荐

