Download a .csv file with Python

前端 未结 2 1222
别那么骄傲
别那么骄傲 2021-01-03 17:13

I am using Python 3.3 on Windows. I am trying to figure out how to download a .csv file from yahoo finance. It is a file for the Historical Prices.

This is the sour

相关标签:
2条回答
  • 2021-01-03 17:19

    You can do this with just urllib. The following code downloads the .csv file and puts the contents into a string named 'csv'. Then it saves the string to a file:

    from urllib import request
    
    # Retrieve the webpage as a string
    response = request.urlopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=1&e=1&f=2014&g=d&a=8&b=7&c=1984&ignore=.csv")
    csv = response.read()
    
    # Save the string to a file
    csvstr = str(csv).strip("b'")
    
    lines = csvstr.split("\\n")
    f = open("historical.csv", "w")
    for line in lines:
       f.write(line + "\n")
    f.close()
    
    0 讨论(0)
  • 2021-01-03 17:34

    since you already use BeautifulSoup and urllib:

    url = BeautifulSoup(html).find('a')['href']
    urllib.urlretrieve(url, '/path/to/downloads/file.csv')
    
    0 讨论(0)
提交回复
热议问题