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

如何用Python从带下载按钮的CIA数据网页下载CSV文件

解决方法

1. 定位真实下载链接

点击页面上的“Download Data”按钮时,打开浏览器开发者工具(快捷键F12)切换到Network标签,筛选“XHR”或“Document”类型请求,就能捕捉到按钮触发的实际下载请求。该请求的URL就是CSV文件的直接访问地址(实际地址以抓包结果为准,通常是类似https://www.cia.gov/the-world-factbook/resource/downloads/country_data_codes.csv的路径)。

2. Python自动下载实现

拿到真实URL后,用requests库即可完成自动下载,示例代码如下:

import requests
from datetime import datetime

def download_cia_country_codes():
    # 替换为抓包获取的真实CSV文件URL
    csv_url = "https://www.cia.gov/the-world-factbook/resource/downloads/country_data_codes.csv"
    # 模拟浏览器请求头,避免被反爬拦截
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    
    try:
        response = requests.get(csv_url, headers=headers)
        response.raise_for_status()  # 校验请求是否成功
        
        # 生成带日期的文件名,便于月度存档
        today = datetime.now().strftime("%Y-%m-%d")
        filename = f"cia_country_codes_{today}.csv"
        
        with open(filename, "wb") as file:
            file.write(response.content)
        
        print(f"文件 {filename} 下载完成")
    except requests.exceptions.RequestException as e:
        print(f"下载失败: {str(e)}")

# 执行下载
download_cia_country_codes()

3. 实现每月自动执行

如果需要每月定时运行,有两种常用方案:

  • 系统级定时任务:Windows使用「任务计划程序」,Linux/macOS使用cron。例如Linux下编辑crontab(执行crontab -e),添加以下配置,每月1号凌晨0点执行脚本:
    0 0 1 * * /usr/bin/python3 /path/to/your/script.py
    
  • Python定时库:用schedule库实现脚本内定时(需保持脚本后台运行),示例片段:
    import schedule
    import time
    
    schedule.every().month.at("00:00").do(download_cia_country_codes)
    
    while True:
        schedule.run_pending()
        time.sleep(60)
    

注意事项

  • 定期校验下载链接:网站可能更新资源路径,建议每隔一段时间重新抓包确认URL有效性。
  • 遵守网站规则:查看https://www.cia.gov/robots.txt确认是否允许爬虫下载该资源,避免违反网站规定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:02:37