我正在尝试从此处运行代码:
Download history stock prices automatically from yahoo finance in python
import urllib
base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
return base_url + ticker_symbol
output_path = "C:/Users/test/Desktop/research/stock_data/test"
def make_filename(ticker_symbol, directory="S&P"):
return output_path + "/" + directory + "/" + ticker_symbol + ".csv"
def pull_historical_data(ticker_symbol, directory="S&P"):
try:
urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
except urllib.ContentTooShortError as e:
outfile = open(make_filename(ticker_symbol, directory), "w")
outfile.write(e.content)
outfile.close()
pull_historical_data('AAPL', directory="S&P")
但出现以下错误:
AttributeError: module 'urllib' has no attribute 'ContentTooShortError'
我如何使它起作用?还是可以指出一些有效的代码?
您需要导入'urllib.request'而不是urllib并按照以下说明更新代码。
urllib.request.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
except urllib.request.ContentTooShortError as e:
import urllib.request
base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
return base_url + ticker_symbol
output_path = "C:/Users/test/Desktop/research/stock_data/test"
def make_filename(ticker_symbol, directory="S&P"):
return output_path + "/" + directory + "/" + ticker_symbol + ".csv"
def pull_historical_data(ticker_symbol, directory="S&P"):
try:
urllib.request.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
except urllib.request.ContentTooShortError as e:
outfile = open(make_filename(ticker_symbol, directory), "w")
outfile.write(e.content)
outfile.close()
pull_historical_data('AAPL', directory="S&P")