首页 > 解决方案 > 使用 Python 从 URL 格式下载 csv:https://.../%Y%m%d.csv 一段时间

问题描述

我是 python 新手,需要一些帮助。

我正在从“ https://.../..._20200110.csv ”下载数据。

我可以使用以下代码下载一个文件:

import requests
import shutil
r = requests.get('https://.../..._20200110.csv', stream=True)
if r.status_code == 200:
    with open("20200110.csv", 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

如何下载 20190131 到 20200102 的数据?

标签: pythoncsvdownload

解决方案


正如 AMC 评论的那样,您的答案在于字符串格式的漫游,例如使用 f-strings (python >3.6)。

此外,您需要在计算月份中的天数时循环日期。因此,您需要将日期字符串转换为某种可以计数的日期对象,例如datetime.

为了帮助您入门:下面的代码应该可以满足您的需求。如果找不到文件,您可能需要添加一些逻辑/反馈。

import requests
import shutil
from datetime import datetime, timedelta

# enter start/end dates here, convert to datetime object
start_date = datetime.strptime('2009-10-31', '%Y-%m-%d')  # the latter arg defines the format of the given string
end_date = datetime.strptime('2011-01-02', '%Y-%m-%d')

# need to know how many days we need to loop over
day_count = (end_date - start_date).days + 1

# loop over days and download file
for i in range(day_count):
    date_str = (start_date + timedelta(i)).strftime('%Y%m%d')  # convert our datetime obj into the desired string format
    r = requests.get(f'https://www.tfx.co.jp/publication/document/daily_statis_{date_str}.csv', stream=True)
    if r.status_code == 200:
        with open(f'{date_str}.csv', 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)

推荐阅读