You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Selenium向文件输入框传入路径?替代PyAutoGUI方案

问题:Selenium操作文件上传/输入框失败,求替代PyAutoGUI的方案

文件上传界面1
文件上传界面2

我需要操作上述界面的输入框,尝试了以下Selenium代码但未成功:

导入的依赖代码

from threading import local
import pandas as pd
import pyautogui
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager 
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

尝试的文件上传代码(存在语法错误)

wait.until(EC.presence_of_element_located((By.XPATH,"//input[@type='file']"))send_keys("C:/Users/my_user/Downloads/doch.jpeg")

尝试的消息输入代码

for index, row in df.iterrows():
    actions.send_keys((row["message"]))
    actions.perform()

目前用PyAutoGUI作为临时方案,但不想继续使用,因为它会占用键盘,导致代码运行时无法操作电脑:

pyautogui.write((row["photo"]))
pyautogui.press("enter")

解决方案

1. 修正文件上传代码的语法与逻辑

原代码存在语法错误,且presence_of_element_located仅保证元素存在于DOM,不确保可见。正确写法:

# 等待文件输入框可见
file_input = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@type='file']")))
# 直接传入文件路径
file_input.send_keys("C:/Users/my_user/Downloads/doch.jpeg")

如果仍失败,排查以下情况:

  • 元素被隐藏:部分网站会隐藏原生file输入框,用自定义按钮触发。需先点击触发按钮,再定位输入框:
    # 点击上传按钮(替换为实际按钮定位器)
    upload_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='上传']")))
    upload_btn.click()
    # 再定位文件输入框并上传
    file_input = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@type='file']")))
    file_input.send_keys("C:/Users/my_user/Downloads/doch.jpeg")
    
  • 输入框在iframe内:需先切换到iframe再操作:
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "iframe-id"))) # 替换为实际iframe的定位器
    file_input = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@type='file']")))
    file_input.send_keys("C:/Users/my_user/Downloads/doch.jpeg")
    driver.switch_to.default_content() # 操作完成切回主文档
    
  • 定位器错误:用浏览器开发者工具验证XPATH,或换用CSS选择器:
    file_input = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[type='file']")))
    

2. 修正消息输入代码

直接定位输入框并使用send_keys比ActionChains更可靠,确保输入框被聚焦:

# 初始化ActionChains(如果需要)
actions = ActionChains(driver)

for index, row in df.iterrows():
    # 定位消息输入框(替换为实际定位器)
    msg_input = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@placeholder='输入消息']")))
    msg_input.clear() # 清空原有内容
    msg_input.send_keys(row["message"])
    # 若需回车发送
    msg_input.send_keys(Keys.ENTER)

内容的提问来源于stack exchange,提问作者Felipe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:05:33