【问题标题】:Keyerror after looping a dictionary循环字典后出现键错误
【发布时间】:2021-07-16 20:13:38
【问题描述】:

我正在对一个以 JSON 格式发回数据的大型数据库进行 api 调用。由于数据很大,数据库将 JSON 数据分批发送,每批包含一个 nextPageUrl: 到下一批。我想循环/爬取批次,收集每个批次的 URL,将它们存储在一个列表中,然后再次循环该列表以解析所有 JSON 数据。然后用解析结果填充我自己的 SQLITE 数据库。但是,我收到此错误消息:

Traceback (most recent call last):
  File "Database_download_v2.py", line 52, in <module>
    if (len(json_dict['nextPageUrl']) > 0): 
KeyError: 'nextPageUrl'

我使用的代码是:

load_page = requests.get(form_response_tree, headers=headers).content
page_decode = load_page.decode()
json_dict = json.loads(page_decode)
url_subseq_page = json_dict['nextPageUrl']
url_list = list()
url_list.append(url_subseq_page)

for all_pages in url_list:
    load_page = requests.get(all_pages, headers=headers).content
    page_decode = load_page.decode()
    json_dict = json.loads(page_decode)
    if (len(json_dict['nextPageUrl']) > 0):
        url_subseq_page = json_dict['nextPageUrl']
        url_list.append(url_subseq_page)
    else:
        continue

知道这里有什么问题吗?

【问题讨论】:

  • 如果没有看到一些 JSON 响应,除了键不存在或您在 nextPageUrl 之前缺少一些键之外,很难回答这个问题。 .get() 是一个 dict 方法,虽然它可以忽略 keyerrors 并且如果没有找到将返回 None。
  • .get 解决方案奏效了!非常感谢!

标签: loops dictionary keyerror


【解决方案1】:

这是因为列表中没有任何内容,因此从技术上讲它不起作用。

解决方案

url_list = ["putstringsinthislist"]

【讨论】:

    猜你喜欢
    • 2020-05-14
    • 2020-10-29
    • 2020-03-02
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多