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

Python+Selenium实现谷歌表单自动提交时executable_path参数报错求助

解决Selenium TypeError及代码优化建议

1. 核心错误:executable_path参数已废弃

Selenium 4.x版本彻底移除了webdriver.Chrome()的executable_path关键字参数,需改用ChromeService类来指定驱动文件路径。

手动指定驱动路径的修改方案

from selenium import webdriver
from selenium.webdriver.chrome.service import Service  # 新增导入

option = webdriver.ChromeOptions()
option.add_argument("-incognito")
option.add_argument("--headless=new")  # 新版Chrome推荐的无头模式参数
option.add_argument("--disable-gpu")  # 补全参数的双短横线格式

# 用Service包装驱动路径
service = Service("/Users/[my name]/chromedriver")
browser = webdriver.Chrome(service=service, options=option)

更便捷的驱动自动管理方案

推荐使用webdriver-manager自动匹配Chrome版本下载驱动,无需手动下载更新:

  1. 先安装依赖包:
pip install webdriver-manager
  1. 修改代码:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

option = webdriver.ChromeOptions()
option.add_argument("-incognito")
option.add_argument("--headless=new")
option.add_argument("--disable-gpu")

# 自动下载并匹配对应版本的ChromeDriver
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=option)

2. 其他代码问题修复

  • 过时的元素定位API:find_element_by_xpath已被废弃,需改用find_element结合By类:
    先导入By类:
    from selenium.webdriver.common.by import By
    
    再修改定位代码:
    # 若需获取多个元素,用find_elements;单个元素用find_element
    otherboxes = browser.find_elements(By.XPATH, "/html/body/div/div[3]/form/div[2]/div/div[2]/div/div/div/div[2]/div/div/span/div/div[1]/label/div/div[1]/div/div[3]/div")
    submitbutton = browser.find_element(By.XPATH, "/html/body/div/div[3]/form/div[2]/div/div[3]/div/div[1]/div/span")
    
  • 元素索引错误:find_element返回单个WebElement对象,不能用[0]索引;如果需要选取多个元素中的第一个,需改用find_elements返回列表后再取索引。
  • 参数格式修正:disable-gpu需改为--disable-gpu,符合Chrome命令行参数的标准格式。

3. 完整修正后代码示例

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

option = webdriver.ChromeOptions()
option.add_argument("-incognito")
option.add_argument("--headless=new")
option.add_argument("--disable-gpu")

browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=option)
browser.get("https://forms.gle/R2xt69eWMnXTGrjD6")

# 检查元素存在后再点击,避免索引报错
otherboxes = browser.find_elements(By.XPATH, "/html/body/div/div[3]/form/div[2]/div/div[2]/div/div/div/div[2]/div/div/span/div/div[1]/label/div/div[1]/div/div[3]/div")
if otherboxes:
    otherboxes[0].click()

submitbutton = browser.find_element(By.XPATH, "/html/body/div/div[3]/form/div[2]/div/div[3]/div/div[1]/div/span")
submitbutton.click()

browser.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:38:10