【问题标题】:Using python to download table data without .csv file address provided使用python下载表格数据,不提供.csv文件地址
【发布时间】:2018-03-08 18:51:58
【问题描述】:

我的目的是从这个网站下载数据: http://transoutage.spp.org/

打开本网站时,在网页底部,有一个说明用于说明如何自动下载数据。例如: http://transoutage.spp.org/report.aspx?download=true&actualendgreaterthan=3/1/2018&includenulls=true

我写的代码是这样的:

 import requests
 ul_begin = 'http://transoutage.spp.org/report.aspx?download=true'

 timeset = '3/1/2018' #define the time, m/d/yyyy 
 fn = ['&actualendgreaterthan='] + [timeset] + ['&includenulls=true']
 fn = ''.join(fn)
 ul = ul_begin+fn

 r = requests.get(ul, verify=False)

既然,如果你输入网址, http://transoutage.spp.org/report.aspx?download=true&actualendgreaterthan=3/1/2018&includenulls=true, 进入 Chrome,它会自动下载 .csv 文件中的数据。我不知道如何继续我的代码。

请帮帮我!!!!

【问题讨论】:

  • 好吧,这行得通吗?它会给出错误吗?它是否在r 中给出了有用的返回值或状态码?
  • 您要查找的数据包含在 r.content 中 - 只是 open 一个文件和 write 它的内容。我刚刚试了一下,它生成了一个有效的 CSV。
  • 你可以使用python的csv模块来处理接收到的csv数据。检查docs.python.org/3.0/library/csv.html

标签: python download request


【解决方案1】:

您需要将收到的响应写入文件:

r = requests.get(ul, verify=False)
if 200 >= r.status_code <= 300: 
    # If the request has succeeded
    file_path = '<path_where_file_has_to_be_downloaded>`
    f = open(file_path, 'w+')
    f.write(r.content)
    f.close()

如果 csv 文件很小,这将正常工作。但是对于大文件,需要使用stream参数下载:http://masnun.com/2016/09/18/python-using-the-requests-module-to-download-large-files-efficiently.html

【讨论】:

  • 非常感谢!!如何设置下载路径?由于没有找到下载文件,我把代码添加到原文件中运行后。
  • @bingqianhu 在此示例中,由于我们没有明确指定路径,因此文件将下载到您运行代码的同一文件夹中。您还可以指定确切的路径 - f = open('/home/ubuntu/Downloads/outfile.csv', 'w+')。相应地编辑了答案
猜你喜欢
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多