使用Selenium操作FRED网站时为何无法点击下拉菜单内的CSV下载子项
问题原因
- 你使用的Selenium旧版API在4.0+版本中已被废弃,执行时会出现不兼容的异常行为
- 点击下载按钮后下拉菜单已经自动展开,多余的
move_to_element操作会导致菜单失活收起,无法触发子项点击 - 代码在点击下载后立刻关闭浏览器,会导致下载任务还没启动就被终止
修复后可运行代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import time # 替换为你本地的chromedriver路径 s = Service(r'D:\\Workspace\\Python\\automation\\chromedriver.exe') # 配置Chrome选项,可按需设置默认下载路径 options = webdriver.ChromeOptions() # 如需指定下载路径取消下行注释并修改路径 # options.add_experimental_option("prefs", {"download.default_directory": "你想要的下载路径"}) driver = webdriver.Chrome(service=s, options=options) url = 'https://fred.stlouisfed.org/series/TERMCBAUTO48NS' driver.get(url) # 等待下载按钮可点击后点击 wait = WebDriverWait(driver, 20) download_btn = wait.until(EC.element_to_be_clickable((By.ID, 'download-button'))) download_btn.click() # 等待CSV下载选项可点击后直接点击 csv_download_btn = wait.until(EC.element_to_be_clickable((By.ID, 'download-data-csv'))) csv_download_btn.click() # 等待3秒保证下载任务启动,再关闭浏览器 time.sleep(3) driver.quit()
额外优化说明
- 如果你不需要模拟浏览器操作,FRED官方提供了公开API可以直接拉取数据,比爬虫更稳定,可自行查阅官方文档配置API密钥调用
- 运行前请确保你的Chrome浏览器版本和chromedriver版本完全匹配,避免出现驱动兼容问题
内容的提问来源于stack exchange,提问作者Raj Aryan
相关产品推荐
相关产品推荐

