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

使用Selenium上传图片至Google Forms遇阻,求解决方案

Google Forms 图片上传Selenium交互问题

使用Selenium向Google Forms上传图片时,已成功打开表单并点击「Add file」按钮触发文件上传弹窗,但无法与弹窗内的type="file"文件输入按钮交互。该按钮在DOM中存在且可见,但Selenium无法对其进行操作。

已尝试的方法

  • 定位按钮:已找到「Add file」和文件输入按钮的正确XPath
  • 等待与延迟:添加显式等待(WebDriverWait)确保元素加载完成后再交互
  • JavaScript执行:尝试直接执行JavaScript触发点击事件,但未解决问题
  • 其他操作:尝试使用switch_to.frame()切换至框架或对话框,也无效果

目前可完成的操作

  • 打开Google Forms
  • 成功点击「Add file」按钮
  • 等待弹窗出现,但卡在图片上传环节

期待任何可行的调整方案或全新解决思路,以下是使用的代码:

import undetected_chromedriver as webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time

# Chrome配置选项
options = webdriver.ChromeOptions()
profile = r"C:\\Users\\User\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 1"
options.add_argument(f"user-data-dir={profile}")
options.add_argument("profile-directory=Profile 1")
driver = webdriver.Chrome(options=options, use_subprocess=True)

try:
    driver.get("https://forms.gle/HcKLXz9ErXkm63qK8")
    print("表单打开成功。")

    # 点击「Add file」按钮
    add_file_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[3]/form/div[2]/div/div[2]/div/div/div/div[2]/div/div[3]/span/span[2]'))
    )
    add_file_button.click()
    print("「Add file」按钮点击成功。")

    # 等待弹窗出现
    popup = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[2]'))  # 弹窗XPath
    )
    print("弹窗已显示。")

    # 定位弹窗内的「Browser」按钮
    browser_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[2]//button[@aria-label="Browser"]'))  # 「Browser」按钮XPath
    )

    # 使用ActionChains确保按钮可交互
    action = ActionChains(driver)
    action.move_to_element(browser_button).click().perform()
    print("「Browser」按钮点击成功。")

    # 等待文件选择对话框打开
    file_input = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '//*[@type="file"]'))  # 文件输入框XPath
    )
    
    # 上传图片
    file_path = "./01.png"
    file_input.send_keys(file_path)
    print(f"图片上传成功:{file_path}")

    # 提交表单
    submit_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[2]/div[3]/div[2]/div[2]/div/div/div/div[1]/div/div[2]/div/button'))
    )
    submit_button.click()
    print("表单提交成功。")

except Exception as e:
    print(f"错误: {e}")
finally:
    driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:30:57