代码之家  ›  专栏  ›  技术社区  ›  Starbucks

创建通过多个URL导入数据的循环

  •  -1
  • Starbucks  · 技术社区  · 6 年前

    https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h 2014 .txt.gz&dir=数据/历史/标准集/

    import urllib
    
    core = 'https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h'
    year = 2014
    end = '.txt.gz&dir=data/historical/stdmet/'
    
    for i in range(0,3):
    
            year += 1
            year_fixed = str(year)
            urllib.urlretrieve(core+year_fixed+end)
    

    AttributeError: module 'urllib' has no attribute 'urlretrieve'
    

    enter image description here

    出于某种原因,它没有导入2014-2017年的任何数据。有没有更好的方法来创建这些数据?任何帮助都将不胜感激。

    2 回复  |  直到 6 年前
        1
  •  2
  •   wiesson    6 年前

    使用python3(这里使用的是3.7)和requests模块,可以简化为:

    import requests
    for year in range(2014, 2018):
        url = f'https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h{year}.txt.gz&dir=data/historical/stdmet/'
        r = requests.get(url)
        print(r.text)
    

    您可以将输出保存到一个文件中,而不是打印

    //为Python编辑<3.6,使用str.format()

    url = "https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h{}.txt.gz&dir=data/historical/stdmet/".format(year)
    

    进一步阅读字符串格式: https://realpython.com/python-f-strings/

        2
  •  0
  •   Irfanuddin    6 年前

    import urllib.request
    
    core = 'https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h'
    year = 2014
    end = '.txt.gz&dir=data/historical/stdmet/'
    
    for i in range(0,3):
    
            year += 1
            year_fixed = str(year)
            filename = "text" + str(i) + ".txt"
            urllib.request.urlretrieve(core+year_fixed+end, filename)