Python爬取USGS地震数据触发JSONDecodeError报错该如何解决?
问题排查及修复方案
你遇到的JSONDecodeError根本原因是请求返回的内容并非合法JSON格式,具体有两个可修复的问题:
- 请求地址错误:你使用的
https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php是服务说明页面,返回HTML内容,无法解析为JSON。需要替换为对应数据维度的geojson地址,例如过去1小时所有地震数据地址为https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson,可按需替换路径中的all_hour为all_day(过去1天)、4.5_week(过去一周4.5级以上地震)等合法值。 - 数据未解码:
webUrl.read()返回的是字节流数据,需要先解码为UTF-8字符串才能传入json.loads()解析。
修复后可运行代码
import urllib.request import json def printResults(data): theJSON = json.loads(data) if "title" in theJSON["metadata"]: print(theJSON["metadata"]["title"]) count = theJSON["metadata"]["count"] print(str(count) + " events recorded") def main(): UrlData = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson" webUrl = urllib.request.urlopen(UrlData) print("result code: " + str(webUrl.getcode())) if webUrl.getcode() == 200: data = webUrl.read().decode('utf-8') printResults(data) else: print("Received error, cannot parse results") if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Asad Ameen
相关产品推荐
相关产品推荐

