Web抓取:在Python中解析JSON时获取KeyError

Web抓取:在Python中解析JSON时获取KeyError,python,json,beautifulsoup,keyerror,Python,Json,Beautifulsoup,Keyerror,我想从网页中提取完整地址,我正在使用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.f

我想从网页中提取完整地址,我正在使用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'}
我想要的是“位置”下的“完整地址”,所以我的代码是:

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号三楼,10013”


非常感谢

您的第一个对象很好,但很明显,您的第二个对象没有
位置
键,也没有
完整地址

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

如果仍要执行循环,则需要使用try/except语句捕获异常,或者使用方法
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 address”


编辑:

数据不一致(从不信任数据)。一些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'))

迭代第二个信息时,没有
位置
输入'props'值'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,USA','s','country','country':'USA','USA','USA','USA','USA','USA','id''17305,'to params','New York's'53、‘地区’:‘城市’:‘纽约’,‘描述’:‘创建地点’:‘2015-01-19T01:32:16.317Z’,‘邮政编码’:‘10013’,‘hq’:True}],‘姓名’:‘LocationsMapList’}@Laura这不是您发布的第二个示例对象。您只需在此页面上按住Ctrl+F键以查看
位置
,它位于第一个对象中,但不在第二个对象中。是的,我只粘贴了输出中的几行。我想要的唯一部分是第一个对象中位置下的完整地址的内容。它在info['props']中的项中遇到另一个错误“--->5”。get('locations',[]):AttributeError:'NoneType'对象没有属性'get'