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

如何用Python下载无.csv地址的网页表格数据(SPP网站示例)

如何用Python下载SPP outage页面的表格数据

我看到你已经找到了SPP outage页面的下载接口——那个带download=true参数的report.aspx链接,浏览器里直接打开能自动导出CSV,但用Python请求可能踩一些小坑。这里给你几个可行的实现方案,帮你顺利拿到数据:

核心思路

这个下载接口本质是通过HTTP GET请求返回CSV格式的文件内容,只要模拟浏览器的请求行为(比如带上必要的请求头),就能用Python直接获取并保存数据。

具体实现代码

方法1:用requests库直接请求(最常用)

这是最直接的方式,关键是要带上浏览器风格的请求头,避免被服务器拦截:

import requests

# 替换成你需要的参数组合,比如调整日期范围
download_url = "http://transoutage.spp.org/report.aspx?download=true&actualendgreaterthan=3/1/2018&includenulls=true"

# 模拟Chrome浏览器的请求头,至少要带上User-Agent
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
}

try:
    # 发送GET请求
    response = requests.get(download_url, headers=headers)
    response.raise_for_status()  # 自动抛出请求失败的异常

    # 将响应内容保存为本地CSV文件
    with open("spp_outage_data.csv", "wb") as file:
        file.write(response.content)
    
    print("数据下载完成,已保存为 spp_outage_data.csv")
except Exception as e:
    print(f"下载失败:{str(e)}")

方法2:用会话维持解决Cookie验证问题

如果遇到服务器返回403禁止访问,可能是需要先访问主页获取会话Cookie,这时候用requests.Session()就能解决:

import requests

download_url = "http://transoutage.spp.org/report.aspx?download=true&actualendgreaterthan=3/1/2018&includenulls=true"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
}

# 创建会话对象,自动维持Cookie
session = requests.Session()
# 先访问主页获取必要的会话信息
session.get("http://transoutage.spp.org/", headers=headers)

try:
    # 通过会话请求下载链接
    response = session.get(download_url, headers=headers)
    response.raise_for_status()

    with open("spp_outage_data.csv", "wb") as file:
        file.write(response.content)
    
    print("数据下载成功!")
except Exception as e:
    print(f"出错了:{str(e)}")

关键注意事项

  • 参数自定义:你可以修改链接里的actualendgreaterthan参数来调整数据的时间范围,格式是MM/DD/YYYY;includenulls设为true会包含空值记录,设为false则过滤掉这类数据。
  • 请求头必要性:一定要带上User-Agent,否则服务器很可能将你的请求识别为非浏览器请求而拒绝。
  • 编码问题:如果打开CSV后出现乱码,可以尝试用response.content.decode('utf-8')解码后再写入文件,这个接口返回的内容一般是UTF-8编码,大多不会有问题。
  • 异常处理:实际使用时建议保留try-except块,处理网络波动、文件权限不足等意外情况。

如果运行代码时遇到具体错误(比如返回内容不是CSV、请求超时),可以把错误信息贴出来,我再帮你排查~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:02:38