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

如何修改Python+Selenium脚本实现动态MP4文件上传?

解决方案:自动获取当前目录下的MP4文件并上传

问题根源

os.path.abspath() 不支持通配符(*.mp4),直接传入会导致无法定位到实际存在的文件,所以脚本执行失败。

实现方案

可以用Python的glob或os模块筛选出目标MP4文件,再获取其绝对路径用于上传,以下是两种可靠的实现方式:

方式一:使用glob模块(推荐,代码更简洁)

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

file_input = browser.find_element(By.XPATH, '//*[@id="content"]/input')
# 匹配当前工作目录下所有MP4文件
mp4_files = glob.glob(os.path.join(os.getcwd(), "*.mp4"))

# 处理文件匹配结果
if len(mp4_files) == 1:
    abs_path = mp4_files[0]
    file_input.send_keys(abs_path)
elif len(mp4_files) > 1:
    print("当前目录存在多个MP4文件,请检查后重试")
else:
    print("当前目录未找到MP4文件")

方式二:使用os模块遍历筛选

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

file_input = browser.find_element(By.XPATH, '//*[@id="content"]/input')
current_dir = os.getcwd()
# 遍历目录,筛选出后缀为MP4的文件(不区分大小写)
mp4_files = [
    os.path.join(current_dir, filename) 
    for filename in os.listdir(current_dir) 
    if filename.lower().endswith(".mp4")
]

# 处理文件匹配结果
if len(mp4_files) == 1:
    abs_path = mp4_files[0]
    file_input.send_keys(abs_path)
elif len(mp4_files) > 1:
    print("当前目录存在多个MP4文件,请检查后重试")
else:
    print("当前目录未找到MP4文件")

额外说明

  • 两种方案都加入了文件数量判断,避免误传多个文件或找不到文件的情况
  • 如果确定目录下一定只有目标MP4文件,可以简化判断逻辑,直接取列表第一个元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:45:27