gpt4 book ai didi

python - 网页抓取 : getting KeyError when parsing JSON in Python

转载 作者:行者123 更新时间:2023-11-30 22:29:45 25 4
gpt4 key购买 nike

我想从网页中提取完整地址,并且我正在使用 BeautifulSoup 和 JSON。这是我的代码:

import bs4
import json
from bs4 import BeautifulSoup
import requests

url = 'xxxxxxxxxxxxxxxxx'
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')

for i in soup.find_all('div', attrs={'data-integration-name':'redux-container'}):
info = json.loads(i.get('data-payload'))

我打印了“信息”:

{'storeName': None, 'props': {'locations': [{'dirty': False, 'updated_at': '2016-05-05T07:57:19.282Z', 'country_code': 'US', 'company_id': 106906, 'longitude': -74.0001954, 'address': '5 Crosby St  3rd Floor', 'state': 'New York', 'full_address': '5 Crosby St  3rd Floor, New York, 10013, New York, USA', 'country': 'United States', 'id': 17305, 'to_params': 'new-york-us', 'latitude': 40.719753, 'region': '', 'city': 'New York', 'description': '', 'created_at': '2015-01-19T01:32:16.317Z', 'zip_code': '10013', 'hq': True}]}, 'name': 'LocationsMapList'}

我想要的是“location”下的“full_address”,所以我的代码是:

info = json.loads(i.get('data-payload'))
for i in info['props']['locations']:
print (i['full_address'])

但是我收到了这个错误:

----> 5     for i in info['props']['locations']:

KeyError: 'locations'

我想打印完整的地址,即“5 Crosby St 3rd Floor, New York, 10013, New York, USA”。

非常感谢!

最佳答案

您正在解析的数据似乎不一致,键并不在所有对象中。

如果您仍然想执行循环,则需要使用 try/except 语句来捕获异常,或者在查找 key 时使用方法 get 来设置回退一本可能不在这里的字典。

info = json.loads(i.get('data-payload'))
for item in info['props'].get('locations', []):
print (item.get('full_address', 'no address'))
<小时/>

get('locations', []) :如果键 location 不存在,则返回空列表,因此循环不会运行任何迭代。

get('full_address', 'no address') :如果没有这样的键,则返回“no adress”

<小时/>

编辑:

数据不一致(永远不要相信数据)。一些 JSON 对象有一个键 props 和一个 null/None 值。下一个修复应该会纠正这个问题:

info = json.loads(i.get('data-payload'))
if info.get('props'):
for item in info['props'].get('locations', []):
print (item.get('full_address', 'no address'))

关于python - 网页抓取 : getting KeyError when parsing JSON in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46259430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com