You need to enable JavaScript to run this app. Python Selenium点击Chartink CSV下载按钮后如何获取文件名并加载至Pandas
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium点击Chartink CSV下载按钮后如何获取文件名并加载至Pandas

自动识别下载CSV并加载到Pandas的实操方案

前置改造:固定Chrome下载路径

你之前的代码没有指定Chrome的下载目录,默认会把文件存到系统下载文件夹,后续找文件会非常麻烦。需要在初始化Chrome驱动时,增加下载配置,把所有自动下载的文件统一存到你指定的固定目录:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
import time
import pandas as pd

# 定义固定的下载存储目录
download_dir = os.path.abspath("./chartink_local_storage")
# 目录不存在则自动创建
os.makedirs(download_dir, exist_ok=True)

# 配置Chrome下载参数
chrome_options = Options()
download_prefs = {
    "download.default_directory": download_dir,  # 指定默认下载位置
    "download.prompt_for_download": False,  # 关闭下载前的确认弹窗
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
}
chrome_options.add_experimental_option("prefs", download_prefs)

DRIVER_PATH = r"C:\Users\u123456\Downloads\chromedriver\chromedriver.exe"
# 初始化带下载配置的驱动
d = webdriver.Chrome(executable_path=DRIVER_PATH, options=chrome_options)

点击下载后自动识别对应CSV文件

不需要提前猜网站生成的CSV文件名,只要在点击下载按钮后,等待文件下载完成,再从固定目录里找修改时间最新的完整CSV文件即可,这种方法兼容性最好,不会因为网站改文件名规则就失效:

# 打开目标页面
d.get('https://chartink.com/screener/copy-supertrend-negative-breakout-1103')

# 定位并点击下载按钮(已验证可用的逻辑)
download_btn = d.find_element_by_link_text("Download csv")
download_btn.click()

# 轮询等待下载完成(最多等待30秒)
wait_deadline = time.time() + 30
target_csv_path = None
while time.time() < wait_deadline:
    matched_files = []
    # 遍历下载目录下的所有文件
    for file_name in os.listdir(download_dir):
        full_path = os.path.join(download_dir, file_name)
        # 跳过Chrome下载中生成的临时.crdownload后缀文件,只识别完整的.csv文件
        if os.path.isfile(full_path) and file_name.endswith(".csv"):
            matched_files.append(full_path)
    if matched_files:
        # 按文件修改时间倒序排序,取最新的那个文件
        matched_files.sort(key=lambda path: os.path.getmtime(path), reverse=True)
        target_csv_path = matched_files[0]
        break
    # 每0.5秒检查一次
    time.sleep(0.5)

加载CSV到Pandas DataFrame

识别到目标文件路径后,直接用pandas读取即可:

if target_csv_path:
    stock_df = pd.read_csv(target_csv_path)
    print(f"成功加载文件:{target_csv_path},共{len(stock_df)}条数据")
    # 打印前5行验证加载结果
    print(stock_df.head())
else:
    print("下载超时,请检查网络连接或页面交互逻辑")

注意:你最初写的pd.read_html(d.find_element_by_class_name(...))逻辑是错误的——pd.read_html是用来解析HTML里的表格元素的,传过去按钮元素的DOM结构,根本不是表格内容,自然无法拿到正确的按钮对象。你后续用find_element_by_link_text("Download csv")定位的逻辑完全可用,不需要额外调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 12:36:09