如何排除来自 json 站点的 if 和 else 语句的按键错误

How to except a keyerror duing if and alse statments from a json site

我正在抓取一个文本 .json 站点以获取信息,有时我正在监视的元素会消失,因为它们不需要存在。这使得程序停止并且无法重新启动,因为它们已经消失了。我需要能够排除他们不存在并继续打印/发送正确的信息。

我尝试用 except KeyError: 做一些事情,但我做的好像不对。

如果有人能帮助我,那就太棒了!注:我把端点拿出来了!

没有一直显示的特别元素是,PIDReleaseTypeTime

def check_endpoint():

    endpoint = ""
    req = requests.get(endpoint)
    reqJson = json.loads(req.text)
    for id in reqJson['threads']:  # For each id in threads list
        PID = id['product']['globalPid']  # Get current PID
        if PID in list:
            print('checking for new products')

        else:
            title = (id['product']['title'])    
            Image = (id['product']['imageUrl'])
            ReleaseType = (id['product']['selectionEngine'])
            Time = (id['product']['effectiveInStockStartSellDate'])
            send(title, PID, Image, ReleaseType, Time)
            print ('added to database'.format(PID))
            list.append(PID)  # Add PID to the list
    return

如果我 运行 现在的代码,我会得到当前的错误。这是我想要排除的元素。

Traceback (most recent call last):
  File "C:\Users\Desktop\Final.py", line 89, in 
<module>
main()
  File "C:\Users\Desktop\Final.py", line 84, in 
main
    check_endpoint()
  File "C:\Users\Desktop\Final.py", line 74, in 
check_endpoint
    ReleaseType = (id['product']['selectionEngine'])
KeyError: 'selectionEngine'

那么你想要这样的东西(请更改 list 变量的名称,见评论)

def check_endpoint():

    endpoint = ""
    req = requests.get(endpoint)
    reqJson = json.loads(req.text)
    for id in reqJson['threads']:  # For each id in threads list
        PID = id['product']['globalPid']  # Get current PID
        if PID in list:
            print('checking for new products')

        else:
          try:
            title = (id['product']['title'])    
            Image = (id['product']['imageUrl'])
            ReleaseType = (id['product']['selectionEngine'])
            Time = (id['product']['effectiveInStockStartSellDate'])

          except KeyError as e:
            print("... ", e)

          else:
            # When all OK ...
            send(title, PID, Image, ReleaseType, Time)
            print ('added to database: {}'.format(PID))
            list.append(PID)  # Add PID to the list

您希望它精确到什么程度取决于您。你可以用不同的方式处理事情。

解决 Python 中的 KeyError 响应的一个好方法是在字典上使用 .get() 方法。如果你调用get方法,你可以提供一个默认值来提供如果key在字典中不存在:

>>> d = {'hi': 'there'}
>>> d.get('hi', 'cats') # return 'cats' if 'hi' is missing
'there'
>>> d.get('apples', 'cats') # return 'cats' if 'apple' is missing
'cats'

如果您有嵌套词典,您可以将 {} 设置为从一个词典提供的默认值,这样您就可以在每个子词典上继续调用 .get()

>>> d = {}
>>> d['a'] = {}
>>> d['a']['b'] = 'c'

>>> d.get('a', {}).get('b', 'cats')
'c'
>>> d.get('x', {}).get('y', 'cats')
'cats'

您可以使用 dict 类型的 .get(key[, default]) 方法(参见 docs here)并设置默认值,而不是从带方括号的字典中获取值。例如:

id['product'].get('selectionEngine', None)

如果 id['product'] 有键 'selectionEngine',这将给出 id['product']['selectionEngine'],否则将给出 None。当然,您可以将 None 更改为其他可能对您的应用程序更有意义的值。