英文:
Using Exception to avoid yahoofinance error
问题
代码中的问题在于使用了错误的异常类。要获得期望的输出,你需要捕获 yf.utils.exceptions.HTTPError
异常,而正确的异常类应该是 yfinance.exceptions.HTTPError
。以下是修正后的代码和期望的输出:
import yfinance as yf
stcks = ['AXSM', 'FB', 'AAPL']
for i in stcks:
try:
sec = yf.Ticker(i).info['sector']
except yf.exceptions.HTTPError as err:
print('error')
continue
else:
print('hi')
修正后的代码应该输出:
hi
error
hi
这样,当无法获取列表中某个项目的数据时,代码将继续迭代处理下一个项目。
英文:
I'm simply trying to use an exception to handle HTTPErrors for items like 'FB' to continue iterating through the list but I can't seem to get around the issue. Code:
stcks = ['AXSM', 'FB', 'AAPL']
for i in stcks:
try:
sec = yf.Ticker(i).info['sector']
except yf.utils.exceptions.HTTPError as err:
print('error')
continue
else:
print('hi')
Output
hi
HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v10/finance/quoteSummary/FB?modules=summaryProfile%2CfinancialData%2CquoteType%2CdefaultKeyStatistics%2CassetProfile%2CsummaryDetail&ssl=true
During handling of the above exception, another exception occurred:
AttributeError
Traceback (most recent call last)
Cell In[243], line 5
3 try :
4 sec = yf.Ticker(i).info['sector']
----> 5 except yf.utils.exceptions.HTTPError as err:
6 print('error')
7 continue
AttributeError: module 'yfinance.utils' has no attribute 'exceptions'
How can I get the desired output provided that I cannot get data for one of the items in the list?:
hi
hi
答案1
得分: 1
使用requests
异常来捕获缺失的股票代码(HTTPError
):
import requests
stcks = ['AXSM', 'FB', 'AAPL']
for i in stcks:
try:
sec = yf.Ticker(i).info['sector']
except requests.HTTPError as err:
print('error')
continue
else:
print('hi')
输出:
hi
error
hi
英文:
Use requests
exception to catch missing tickers (HTTPError
):
import requests
stcks = ['AXSM', 'FB', 'AAPL']
for i in stcks:
try:
sec = yf.Ticker(i).info['sector']
except requests.HTTPError as err:
print('error')
continue
else:
print('hi')
Output:
hi
error
hi
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论