如何使用BeautifulSoup提取JSON中的boundedBy和coordinates属性?
解决方法
你当前的问题在于用BeautifulSoup解析JSON数据——BeautifulSoup是专门处理HTML/XML的工具,而这个Yandex地图搜索接口返回的是JSON格式的数据,完全不需要用到它。直接解析JSON即可提取目标字段,具体代码如下:
import fake_useragent import requests ua = fake_useragent.UserAgent() url = "https://search-maps.yandex.ru/v1/?text=%D0%9F%D0%BE%D1%87%D1%82%D0%B0%20%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8,%20%D0%9A%D1%80%D0%B0%D1%81%D0%BD%D0%BE%D0%B4%D0%B0%D1%80&results=500&type=biz&lang=ru_RU&apikey=d9168899-cf24-452a-95cf-06d7ac5a982b" r = requests.get(url, headers={"User-Agent": ua.random}) # 将响应解析为Python字典 result_data = r.json() # 遍历每个搜索结果条目 for item in result_data.get("features", []): # 提取坐标(geometry下的coordinates字段) coordinates = item.get("geometry", {}).get("coordinates") # 提取边界范围(properties下的boundedBy字段) bounded_by = item.get("properties", {}).get("boundedBy") # 输出提取的内容 print(f"坐标: {coordinates}") print(f"边界范围: {bounded_by}") print("-" * 20)
关键说明
- 用
r.json()直接把接口返回的JSON字符串转换成Python字典,这是处理JSON接口的标准方式。 - 使用字典的
get()方法可以避免因字段不存在导致的报错,提升代码稳定性。 - 搜索结果都嵌套在
features数组中,每个条目里的geometry.coordinates是坐标数据,properties.boundedBy是边界范围数据。
内容的提问来源于stack exchange,提问作者odo sd
相关产品推荐
相关产品推荐

