You need to enable JavaScript to run this app. 如何使用Python Selenium自动获取最新版本CSV的href链接
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Selenium自动获取最新版本CSV的href链接

自动抓取NUCC分类CSV最新版下载链接实现方案

原有测试代码直接抓取所有li a标签的方式,会匹配到大量无关的导航、侧边栏链接,无法精准定位目标CSV文件,可按以下逻辑调整实现自动抓取:

  • 核心匹配逻辑:NUCC官网的历史CSV文件均遵循固定命名规则,即文件名以nucc_taxonomy_开头,后接3位版本号,以.csv结尾,统一存储在官网的CSV资源目录下
  • 实现流程:
    1. 遍历页面所有a标签的href属性,过滤出符合上述命名格式的链接
    2. 提取每个链接对应的版本号数值,按版本号从高到低排序,排序后的第一个链接即为最新发布的版本
    3. 只要NUCC后续更新CSV时保持现有命名规则不变,程序就可以自动识别最新版链接,无需手动修改版本号或人工查找

调整后可直接运行的代码

from selenium import webdriver
import re

home_page1 = "https://www.nucc.org/index.php/code-sets-mainmenu-41/provider-taxonomy-mainmenu-40/csv-mainmenu-57"
driver = webdriver.Chrome("xx\\xx\\chromedriver.exe")
driver.get(home_page1)

# 定义匹配目标CSV链接的正则规则
csv_link_pattern = re.compile(r"nucc_taxonomy_(\d+)\.csv$")
candidate_links = []

for link_elem in driver.find_elements_by_css_selector("a"):
    href = link_elem.get_attribute("href")
    if not href:
        continue
    match_result = csv_link_pattern.search(href)
    if match_result:
        current_version = int(match_result.group(1))
        candidate_links.append((current_version, href))

# 按版本号倒序排序,取最高版本对应的链接即为最新版
if candidate_links:
    candidate_links.sort(reverse=True, key=lambda item: item[0])
    latest_download_url = candidate_links[0][1]
    print(latest_download_url)
else:
    print("未识别到符合规则的NUCC分类CSV文件链接")

方案优势:无需硬编码版本号,也不依赖页面具体的元素层级结构,即便后续官网调整页面排版,只要保持CSV文件的命名规则不变,程序就能稳定抓取最新版链接,不会受无关页面元素干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 02:45:03