如何通过按钮下载网页CSV?DefiLlama下载失败的解决方案
解决DefiLlama链数据CSV下载问题
原代码的问题分析
- 动态class名不可靠:
sc-8f0f10aa-1是前端框架动态生成的类名,网站更新后会直接失效,导致元素定位失败 - 依赖缺失:代码中使用了
time.sleep()但未导入time模块,会触发运行报错 - 等待策略不足:仅用隐式等待无法确保按钮完全加载并处于可点击状态
- Chrome下载配置不全:未设置CSV文件的自动下载规则,可能弹出下载确认框导致流程中断
方案一:优化Selenium代码
改用更稳定的元素定位方式,补充完整的Chrome下载配置,添加显式等待确保元素可交互:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # 配置Chrome下载参数 options = webdriver.ChromeOptions() prefs = { "download.default_directory": "D:/Profession/Data Extraction and Web Scraping/Stocks Data Extraction - Core Scientific/Output", "download.prompt_for_download": False, # 禁用下载确认弹窗 "download.directory_upgrade": True, "plugins.always_open_pdf_externally": True, # 确保非PDF文件直接下载 "profile.content_settings.exceptions.automatic_downloads.*.setting": 1 } options.add_experimental_option("prefs", prefs) # 新版Selenium无需手动指定executable_path,会自动匹配本地ChromeDriver driver = webdriver.Chrome(options=options) try: driver.get("https://defillama.com/chains") # 显式等待按钮加载完成并可点击,通过按钮文本精准定位 download_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[text()='Download all data in .csv']")) ) download_button.click() time.sleep(5) # 预留时间确保文件下载完成 finally: driver.quit()
方案二:直接请求CSV接口(推荐,更高效)
无需启动浏览器,直接调用平台提供的CSV下载接口,用requests库完成下载:
import requests csv_url = "https://api.llama.fi/chains/download" save_path = "D:/Profession/Data Extraction and Web Scraping/Stocks Data Extraction - Core Scientific/Output/chains_data.csv" response = requests.get(csv_url) response.raise_for_status() # 检查请求是否成功 with open(save_path, "wb") as f: f.write(response.content) print("CSV文件下载完成")
此方法跳过浏览器渲染流程,速度更快,且不受前端页面结构变更影响,稳定性更强。
内容的提问来源于stack exchange,提问作者Steel8
相关产品推荐
相关产品推荐

