python - 在我的情况下如何忽略 KeyError?(Python)
问题描述
在使用具有空白或“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'])
但我仍然得到错误。非常感谢帮助。
解决方案
推荐阅读
- apache-flink - Flink:我们可以只更新 processBroadcastElement 函数中某些元素的键控状态吗?
- sql - 将 Ruby 数组作为值传递给 SQL
- flutter - Flutter 中是否有等效的引导容器?
- javascript - 在 vue js 中的组件之间传递数组
- python - 如何实现按给定优先级对项目进行排序的队列?
- python - 将字符串拆分为numpy数组
- jupyter-lab - 具有共享存储的集群上的 Jupiter Lab
- bash - 不同shell中的不同环境
- android - 如何在 Android Studio 中将 Replit DART 代码转换为应用程序
- jekyll - 如果相关帖子为空,请不要打印页面上的H1