问题描述
在使用具有空白或“NA”值的字典时,我试图忽略我的情况下的 KeyError 或其他类型的错误。
这是我的代码。该错误来自使用“CCIV”等股票时,该股票在雅虎财经中没有员工人数。此外,有时有些公司会将董事会成员的薪酬设为“NA”。
# first attempt at something
import requests
from bs4 import BeautifulSoup
import json
import re
from io import StringIO
url_profile = 'https://finance.yahoo.com/quote/{}/profile?p={}'
stock = input("\n\tStock :\t")
# -------- NLP to stock ticker -------------
# Work in progress
# -------- NLP to stock ticker -------------
response = requests.get(url_profile.format(stock,stock))
soup = BeautifulSoup(response.text,'html.parser')
pattern = re.compile(r'\s--\sData\s--\s')
script_data = soup.find('script',text = pattern).contents[0]
start = script_data.find('context')-2
json_data = json.loads(script_data[start:-12])
if ValueError or KeyError:
pass
# ---- Ticker
symbol = json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['symbol']
# ---- Employees
employees = str(json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['assetProfile']['fullTimeEmployees']
# ---- Titles
title = []
for i in range(3):
title.append(json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['assetProfile']['companyOfficers'][i]['title'])
# ---- Names
name = []
for i in range(3):
name.append(json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['assetProfile']['companyOfficers'][i]['name'])
# ---- Ages
age = []
for i in range(3):
age.append(str(json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['assetProfile']['companyOfficers'][i]['age']))
# ---- Pay
pay = []
for i in range(3):
pay.append(json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['assetProfile']['companyOfficers'][i]['totalPay']['longFmt'])
# ---- Formatting (cred. "Anon Coward")
rows = [
["Ticker :",symbol],["Employees :",employees],["Title :",title[0],title[1],title[2]],["Name :",name[0],name[1],name[2]],["Ages :",age[0],age[1],age[2]],["Pay :",pay[0],pay[1],pay[2]],]
# Build up a max length of each column
lengths = {}
for row in rows:
for i in range(len(row)):
lengths[i] = max(lengths.get(i,0),len(row[i]))
for row in rows:
# For each cell,padd it by the max length
output = ""
for i in range(len(row)):
if len(output) > 0:
# Add a space between columns
output += " "
cell = row[i] + " " * lengths[i]
cell = cell[:lengths[i]]
output += cell
print(output+"\n")
我尝试过类似的事情:
employees = 0
if str(json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['assetProfile']['fullTimeEmployees']) != KeyError:
employees = str(json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['assetProfile']['fullTimeEmployees'])
但我仍然收到错误消息。非常感谢帮助。
解决方法
KeyError 异常是当您尝试访问不在字典中的键时引发的异常
你可以使用 try/except
https://realpython.com/python-keyerror/
,如果您正在寻找一种更简单的方法来获取这些数据,您可以尝试一个名为 yahooquery 的包。免责声明:我是包的作者。
from yahooquery import Ticker
t = Ticker('CCIV')
t.company_officers
maxAge name age title yearBorn exercisedValue unexercisedValue
symbol row
CCIV 0 1 Mr. Michael S. Klein 56 Chairman,CEO & Pres 1964 0 0
1 1 Mr. Lee Jay Taragin 54 Chief Financial Officer 1966 0 0