首页 > 解决方案 > 在我的情况下如何忽略 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'])

但我仍然得到错误。非常感谢帮助。

标签: pythonlisterror-handlingyahoo-financekeyerror

解决方案


KeyError 异常是当您尝试访问不在字典中的键时引发的

你可以使用 try/except

https://realpython.com/python-keyerror/


推荐阅读