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

使用Selenium模拟点击NSEIndia网站CSV下载链接失败求助

NSEIndia债券交易页面CSV自动下载问题排查与修复

你的代码点击无效主要是元素定位不准确、页面加载不充分或交互方式不当导致,以下是具体修复方案:

1. 替换不可靠的元素定位方式

By.LINK_TEXT要求文本完全匹配,页面元素可能存在空格、换行或隐藏字符导致匹配失败。改用更灵活的XPATH定位,匹配包含目标文本的元素:

e1 = driver1.find_element(By.XPATH, "//*[contains(text(), 'Download (.csv)')]")

如果知道元素的class或其他属性,也可以用更精确的CSS选择器:

# 假设下载按钮的class为"csv-download-btn"
e1 = driver1.find_element(By.CSS_SELECTOR, ".csv-download-btn")

2. 用显式等待替代固定睡眠

固定的time.sleep(2)无法确保元素完全加载完成,改用WebDriverWait等待元素可点击,提升稳定性:
先导入相关模块:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

替换原有的等待和定位代码:

driver1.get(Base_Link)
driver1.maximize_window()
# 等待最多10秒,直到元素可点击
e1 = WebDriverWait(driver1, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'Download (.csv)')]"))
)

3. 确保元素可见再点击

部分元素可能在页面下方,需要先滚动到元素位置再执行点击:

# 滚动到元素可见
driver1.execute_script("arguments[0].scrollIntoView();", e1)
# 直接点击元素(比execute_script更符合正常交互逻辑)
e1.click()

4. 修复路径转义问题

你的ChromeDriver路径使用单反斜杠可能导致转义错误,改用原始字符串或双反斜杠:

s = Service(r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
# 或者
s = Service('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')

完整修复后的代码

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Base_Link = "https://www.nseindia.com/market-data/bonds-traded-in-capital-market"

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_experimental_option('excludeSwitches', ['enable-logging'])

# 修复路径转义
s = Service(r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
driver1 = webdriver.Chrome(service=s, options=options)

# 设置默认缩放80%
driver1.get('chrome://settings/')
driver1.execute_script('chrome.settingsPrivate.setDefaultZoom(0.8);')

driver1.get(Base_Link)
driver1.maximize_window()

# 显式等待元素可点击
e1 = WebDriverWait(driver1, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'Download (.csv)')]"))
)
# 滚动到元素可见
driver1.execute_script("arguments[0].scrollIntoView();", e1)
# 执行点击
e1.click()

time.sleep(10)
driver1.quit()

额外排查点

  • 检查页面是否有弹窗或遮罩层,若有需先关闭;
  • 确认ChromeDriver版本与Chrome浏览器版本匹配,版本不兼容会导致交互失败;
  • 若元素在iframe内,需先切换到对应iframe再定位元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:45:35