我试着从这里运行代码:
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'我怎么才能让它工作呢?或者你能告诉我一些可以工作的代码吗?
发布于 2019-10-29 18:42:48
你需要导入'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")https://stackoverflow.com/questions/58605579
复制相似问题