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

如何自动化选择浏览器弹出文件管理器中的文件(WhatsApp脚本场景)

WhatsApp Web 图片附件上传解决方案(Selenium)

核心思路

不要尝试控制系统文件管理器弹窗,Selenium原生支持通过定位隐藏的input[type="file"]元素直接传入文件路径,绕过弹窗环节,这是处理网页文件上传的标准可靠方案。

具体实现步骤

  1. 定位隐藏的文件上传Input元素
    WhatsApp Web的照片/视频上传按钮背后,对应一个隐藏的<input>标签,可通过CSS选择器定位(若选择器失效,可通过浏览器F12开发者工具查看最新元素属性)。

  2. 直接传入文件绝对路径
    找到该元素后,调用send_keys()方法传入图片的绝对路径,无需点击上传按钮触发弹窗。

完整代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 初始化Chrome浏览器
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://web.whatsapp.com/")

# 等待扫码登录(可根据网络情况调整等待时间)
time.sleep(10)

# 定位目标聊天窗口(替换为实际聊天名称)
target_chat = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//span[@title="目标聊天名称"]'))
)
target_chat.click()

# 定位文件上传Input元素
file_upload_input = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, 'input[type="file"][accept*="image"]'))
)

# 传入图片绝对路径(Windows用反斜杠/双反斜杠,Linux/macOS用正斜杠)
image_path = "C:/Users/YourName/Desktop/test_image.jpg"
file_upload_input.send_keys(image_path)

# 等待图片加载完成后点击发送(可选,若需自动发送)
time.sleep(3)
send_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//span[@data-icon="send"]'))
)
send_button.click()

# 关闭浏览器(可选)
# driver.quit()

关键注意事项

  • 必须使用绝对路径传入文件,相对路径可能导致识别失败
  • 优先使用WebDriverWait替代time.sleep,提升脚本稳定性,避免因元素未加载完成报错
  • 若WhatsApp Web更新导致选择器失效,打开开发者工具(F12),找到上传按钮对应的<input>标签,更新CSS选择器或XPath

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:20:29