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

Python Selenium 4.6.0 Remote WebDriver文件上传失败求解决方案

解决Selenium 4.6.0 RemoteDriver文件上传失败问题

问题根源

你遇到的报错是因为Selenium 4.x在W3C模式下,文件上传请求的接口路径默认带了/se/前缀(对应/session/$sessionId/se/file),但你的远程WebDriver节点不支持这个带vendor前缀的接口,导致识别失败。

可行解决方案

1. 动态修改RemoteConnection的命令映射(无需修改源码)

在初始化RemoteDriver之前,动态覆盖UPLOAD_FILE命令的接口路径,移除/se/前缀。这样发送文件上传请求时就会使用标准的W3C接口路径/session/$sessionId/file。

from selenium import webdriver
from selenium.webdriver.remote.remote_connection import Command, RemoteConnection
from selenium.webdriver.common.by import By

# 重写文件上传的接口路径,移除se前缀
RemoteConnection.command_executor[Command.UPLOAD_FILE] = ('POST', "/session/$sessionId/file")

# 初始化RemoteDriver
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Remote(
    command_executor="http://你的远程节点地址:4444/wd/hub",
    options=chrome_options
)

# 执行文件上传
driver.find_element(By.XPATH, "//input[@accept]").send_keys("本地文件的绝对路径")

2. 使用官方LocalFileDetector处理远程文件上传

Selenium提供了LocalFileDetector专门用于远程环境下的文件上传,它会自动处理本地文件到远程节点的传输,无需手动处理接口路径问题。

from selenium import webdriver
from selenium.webdriver.remote.file_detector import LocalFileDetector
from selenium.webdriver.common.by import By

# 初始化RemoteDriver
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Remote(
    command_executor="http://你的远程节点地址:4444/wd/hub",
    options=chrome_options
)

# 设置文件检测器
driver.file_detector = LocalFileDetector()

# 执行文件上传
driver.find_element(By.XPATH, "//input[@accept]").send_keys("本地文件的绝对路径")

3. 尝试JS注入(仅适用于无安全限制的场景)

如果上述方法都无效,可以尝试通过JavaScript直接设置文件输入框的value,但注意:现代浏览器大多会阻止这种操作(出于安全限制),仅在测试环境或无限制的页面中可行。

from selenium import webdriver
from selenium.webdriver.common.by import By

# 初始化RemoteDriver
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Remote(
    command_executor="http://你的远程节点地址:4444/wd/hub",
    options=chrome_options
)

# 定位上传输入框并通过JS设置路径
upload_element = driver.find_element(By.XPATH, "//input[@accept]")
file_path = "本地文件的绝对路径"
driver.execute_script("arguments[0].value = arguments[1];", upload_element, file_path)

# 触发上传操作(根据页面实际上传按钮定位)
driver.find_element(By.XPATH, "//button[contains(text(), '上传')]").click()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:25:21