【问题标题】:How to download multiple CSV files off a website using Python?如何使用 Python 从网站上下载多个 CSV 文件?
【发布时间】:2019-08-01 04:15:56
【问题描述】:

我是编程初学者(金融专业),我希望使用 Python 减少手工工作。我想从https://www.nseindia.com/products/content/equities/equities/archieve_eq.htm 下载多个 CSV(过去一年的每日波动率 CSV)

到目前为止,我可以一次下载一个文件。但我无法申请循环下载过去一年的 CSV。此外,如果我可以跳过周六和周日的 CSV 下载,那也会有所帮助。

我制作了一个 csv 文件,其中提到了所有必需 CSV 文件的链接。然后尝试导入该 csv 文件并对其运行 for 循环操作。但我没有足够的编程知识来做到这一点。

import requests
import shutil

r = requests.get('https://nseindia.com/archives/nsccl/volt/CMVOLT_01072018.CSV', stream=True)
if r.status_code == 200:
    with open("01072018.csv", 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

所需结果:根据输入的日期范围下载 CSV 文件。
实际结果:一次下载 1 个 CSV 文件。

【问题讨论】:

  • 我对“预期结果”感到困惑。这段代码不包含循环,那么你怎么能指望它下载多个文件呢?您的意思是说想要的结果吗?
  • 我删除了那部分代码,因为它不起作用。我提到这一点是为了了解我的思考过程。是的,这应该是理想的结果。

标签: python csv


【解决方案1】:
filenames=['https://nseindia.com/archives/nsccl/volt/CMVOLT_01072018.CSV',
'https://nseindia.com/archives/nsccl/volt/CMVOLT_01082018.CSV',
'https://nseindia.com/archives/nsccl/volt/CMVOLT_01092018.CSV',
]

for x in filenames:
    r=requests.get(x, stream=True)
    if r.status_code == 200:
        with open(x.split('_')[-1], 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)

【讨论】:

    【解决方案2】:

    好吧,不用添加另一个库,以下是应该可以工作的代码,即使它在我有一些限制的机器上不起作用。

    import datetime as timer
    import requests
    import shutil
    
    
    def download_data(date):
        url='https://nseindia.com/archives/nsccl/volt/CMVOLT_'+date+'.CSV'
        csv_filename=date+'.csv'
        try:
            print('Calling url:- ' + url)
            r = requests.get(url, stream=True,verify=False)
            if r.status_code == 200:
                with open(csv_filename, 'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw, f)
            r.close()
        except Exception as e:
            print('for Date '+ date +' Exception happened, most probably a weekend, EXCEPTION Message is ' + str(e))
    
    
    
    def code_runner():
        i=0
        now = timer.datetime.now()
        day = now.day
        month = now.month
        year = now.year
        while i<365:
            day=day-1
            if day==0:
                day=31
                month=month-1
                if month==0:
                    month=12
                    year=year-1
            year1=year
            month1='{:02d}'.format(month)
            day1='{:02d}'.format(day)
            date=str(day1)+str(month1)+str(year1)
            download_data(date)
            i+=1
    
    if __name__=='__main__':
        code_runner()
    

    【讨论】:

    • 我不断收到异常消息:异常消息是 HTTPSConnectionPool(host='nseindia.com', port=443):最大重试次数超出了 url:/archives/nsccl/volt/CMVOLT_22072019.CSV(由NewConnectionError(': 无法建立新连接: [WinError 10060] 连接尝试失败,因为连接方在一段时间后没有正确响应,或者连接失败,因为连接的主机没有响应',))我认为这是因为我的机器处于受限环境中。
    【解决方案3】:

    我会为你的脚本添加一个日期循环:

    #!/usr/bin/env ipython
    # --------------------
    import requests
    import shutil
    import datetime
    # -----------------------------------------------------------------------------------
    dates=[datetime.datetime(2019,1,1)+datetime.timedelta(dval) for dval in range(0,366)];
    # -----------------------------------------------------------------------------------
    for dateval in dates:
        r = requests.get('https://www.nseindia.com/archives/nsccl/volt/CMVOLT_'+dateval.strftime('%d%m%Y')+'.CSV', stream=True)
        if r.status_code == 200:
            with open(dateval.strftime('%d%m%Y')+".csv", 'wb') as f:
                r.raw.decode_content = True
                shutil.copyfileobj(r.raw, f)
        # ---------------------------------------------------------------------------------
    

    【讨论】:

    • 这正是我想要的!谢谢。
    猜你喜欢
    • 2016-02-04
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2020-09-13
    • 2019-01-15
    • 2020-07-31
    相关资源
    最近更新 更多