python - 使用 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 的数据?
解决方案
正如 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)
推荐阅读
- python - 如何在 Pyspark 中同时使用 partitionBy 和 orderBy
- scala - 展平具有 Option[T] 值的地图
- python - 使用 python 3 和 Selenium 抓取动态生成的表
- html - 如何在表单中使用 th:object 但在 thymeleaf spring boot 中跳过表单内的字段
- php - 调整大小功能旋转某些图像
- python - 如何对描述事件的混合变量数据框进行聚类?
- java - 如何在由 mvn jetty:run 启动的 Jetty 中设置调试?
- asp.net - 如何对 WCF 主机进行健康检查?
- java - 屏幕锁定时不要停止 webviewer 音频?
- android - 如何修复错误“资源 ID #0x7f0600c3 类型 #0x4 无效”