【发布时间】:2018-02-25 19:38:21
【问题描述】:
我想从网页中提取完整地址,我正在使用 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 Crosby St 3rd Floor, New York, 10013, New York, USA”。
非常感谢!
【问题讨论】:
-
在迭代你的第二个信息时没有
locations'props' 值中的键
标签: python json beautifulsoup keyerror