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

使用Python和Selenium修改日期控件并下载Investing.com的CSV数据

解决Investing.com历史数据下载的Selenium问题

问题核心原因

原代码存在几个关键缺陷:

  • 依赖绝对XPATH,页面结构稍有变动就会失效
  • 未处理Cookie授权弹窗,可能阻塞元素交互
  • 直接用send_keys输入日期未触发控件的更新事件
  • 表格加载的等待条件不合理,导致无限循环

修正后的可运行代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 配置浏览器下载选项(可替换为你的目标下载目录)
options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
    "download.default_directory": "/your/local/download/path",
    "download.prompt_for_download": False,
    "download.directory_upgrade": True
})
browser = webdriver.Chrome(options=options)
browser.maximize_window()
browser.get('https://www.investing.com/equities/barclays-africa-group-ltd-historical-data')

try:
    # 处理Cookie授权弹窗(无弹窗则自动跳过)
    cookie_btn = WebDriverWait(browser, 10).until(
        EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler"))
    )
    cookie_btn.click()
except:
    pass

# 打开日期选择面板
date_toggle = WebDriverWait(browser, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'datePickerWrapper')]//div[contains(@class, 'iconCalendar')]/parent::div"))
)
date_toggle.click()

# 用JavaScript直接设置起始日期,确保触发控件更新
start_date_input = WebDriverWait(browser, 10).until(
    EC.presence_of_element_located((By.NAME, "startDate"))
)
browser.execute_script("arguments[0].value = '01/01/2012';", start_date_input)

# 点击应用按钮更新数据
apply_btn = WebDriverWait(browser, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//button[@data-test='daterange-apply-button']"))
)
apply_btn.click()

# 等待表格加载完成:判断第一行日期不是默认的最新日期
WebDriverWait(browser, 20).until(
    lambda driver: driver.find_element(By.XPATH, "//table[@data-test='historical-data-table']//tbody/tr[1]/td[1]").text != "01/30/2023"
)

# 点击CSV下载按钮
download_btn = WebDriverWait(browser, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//a[@data-test='data-download-link']"))
)
download_btn.click()

# 等待下载完成(根据网络情况调整时长)
time.sleep(5)

finally:
    browser.quit()

关键优化说明

  • Cookie处理:优先处理网站的Cookie授权,避免弹窗遮挡操作元素
  • 相对定位:使用ID、name、data-test等属性构建相对XPATH,提升代码稳定性
  • JS设置日期:绕过常规输入的交互限制,直接修改输入框值并触发控件更新
  • 合理等待:通过表格内容变化判断数据加载完成,避免无限等待

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:10:29