我无法访问Yahoo Finance。我收到401访问错误。 你能帮忙吗?
from urllib import request
biib_url = 'https://query1.finance.yahoo.com/v7/finance/download/BIIB?period1=1463674892&period2=1495210892&interval=1d&events=history&crumb=DHH18j0z8Nl'
def download_stock_data(csv_url):
response = request.urlopen(csv_url)
csv = response.read()
csv_str = str(csv)
lines = csv_str.split("\\n")
dest_url = r'biib.csv'
fx = open(dest_url, "w")
for line in lines:
fx.write(line + "\n")
fx.close()
download_stock_data(biib_url)
答案 0 :(得分:1)
将您的代码更改为此。
#~ from urllib import request
import requests
biib_url = 'https://query1.finance.yahoo.com/v7/finance/download/BIIB?period1=1463674892&period2=1495210892&interval=1d&events=history&crumb=DHH18j0z8Nl'
def download_stock_data(csv_url):
#~ response = request.urlopen(csv_url)
#~ csv = response.read()
#~ csv_str = str(csv)
csv_str = requests.get(csv_url).text
lines = csv_str.split("\\n")
dest_url = r'biib.csv'
fx = open(dest_url, "w")
for line in lines:
fx.write(line + "\n")
fx.close()
download_stock_data(biib_url)
换句话说,请使用requests
代替(较旧的)urllib
。你的生活会轻松多了。