python - 如何在 Python 中忽略“KeyError”
问题描述
我正在尝试使用 api“yfinance”分析 python 中的股票。我让程序在大多数情况下都能正常运行。但是,当它无法“找到”其中一个字段时,它会出现错误(KeyError)。这是我的代码片段。
import yfinance as yf
stock = yf.Ticker(stock)
pegRatio = stock.info['pegRatio']
print(pegRatio)
if pegRatio > 1:
print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")
这是错误 Traceback(最近一次调用最后一次):第 29 行,industry = stock.info['industry'] KeyError: 'industry'
我的主要问题是如何让代码基本上忽略错误并运行其余代码?
解决方案
Python 中的错误处理
就像Nicolas已经评论过的那样,您会在网络上找到许多教程、博客文章和视频。还有一些涵盖“错误处理”的基本 Python 书籍。
Python 中的控制结构至少包含 2 个关键字try
和except
,通常命名为try-except block。还有 2 个可选关键字else
和finally
.
如何包装你的失败陈述
import yfinance as yf
try: # st art watching for errors
stock = yf.Ticker(stock) # the API call may also fail, e.g. no connection
pegRatio = stock.info['pegRatio'] # here your actual exception was thrown
except KeyError: # catch unspecific or specific errors/exceptions
# handling this error type begins here: print and return
print "Error: Could not find PEG Ratio in Yahoo! Finance response!"
return
# the happy path continues here: with pegRatio
print(pegRatio)
if pegRatio > 1:
print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")
推荐阅读
- android - 创建新密钥库时 Visual Studio 崩溃
- bash - 如何将 gitbash 与包含 ASCII 感叹号字符(如 !0-MyFolder)的文件名一起使用
- java - 为对象创建特定的时间戳?
- excel - 尝试从字符串中提取 6 或 5 位数字
- javascript - 关于全局对象的几个问题
- ruby-on-rails - Rails 创建一个简单的函数以在系统范围的控制台中运行
- javascript - 一组正方形的响应宽度和高度
- android - 如何在 Calllback 上切换 Kivy 布局?
- java - ReentrantLock - lock.unlock() 不释放锁
- python-3.x - 无法使用 XPATH python 从脚本标签中抓取 JSON