Python中使用selenium上传文件时提示“未找到文件”如何解决?

这是我的代码, 上传文件的时候无论是

input_field.send_keys(r'D:\MyPython\DownloadGooglePic\save.png') or

# input_field.send_keys(r'D:/MyPython/DownloadGooglePic/save.png')

都会显示没有找到文件的错误, 请问如何解决这个问题?

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import urllib.request
import datetime
import glob
import os
import re
from PIL import ImageGrab
# im = ImageGrab.grabclipboard()
# im.save('save.png','PNG')

list_of_files = glob.glob(‘c:/clippic/*’) # * means all if need specific format then *.csv latest_file = max(list_of_files, key=os.path.getctime) latest_file = re.sub(r"/", r"\", latest_file) latest_file = re.sub(r"\", r"/", latest_file)

if os.path.exists(‘OCRFile.txt’):

os.remove(‘OCRFile.txt’)

with open(‘OCRFile.txt’, ‘a’) as the_file:

the_file.write(latest_file)

with open(‘OCRFile.txt’) as the_file: wordlist = the_file.read().splitlines()

driver = webdriver.Firefox() url = “http://zhcn.109876543210.com/” driver.get(url) input_field = driver.find_element_by_css_selector(‘div#container input[type=“file”]’)

input_field.send_keys(r’D:\MyPython\DownloadGooglePic\save.png’)

input_field.send_keys(r’D:/MyPython/DownloadGooglePic/save.png’)


Python中使用selenium上传文件时提示“未找到文件”如何解决?

3 回复

遇到Selenium上传文件报“未找到文件”,通常是路径问题或元素定位不对。

核心解决方案:

  1. 使用绝对路径:不要用相对路径,用os.path.abspath()转换。
  2. 直接send_keys文件路径:找到<input type="file">元素直接传路径,别用pyautogui等模拟操作。

示例代码:

from selenium import webdriver
import os

driver = webdriver.Chrome()
driver.get("你的上传页面URL")

# 定位文件上传input元素
file_input = driver.find_element("xpath", "//input[@type='file']")

# 构建绝对路径
file_path = os.path.abspath("你的文件.txt")

# 发送文件路径
file_input.send_keys(file_path)

# 后续提交操作...

注意:

  • 确保文件确实存在于该路径。
  • 如果页面是动态加载的,可能需要等待元素出现。

一句话总结: 用绝对路径直接send_keys到file类型的input元素。


用 Chrome 没有问题, 用 firefox 错误~

进入 DownloadGooglePic 这个目录 然后 input_field.send_keys(‘save.png’) 试试

回到顶部