如何从网站获取JSON数据,但响应无

2024-04-20 11:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从它们的API获取数据映射,它们的格式输出是JSON

我编写的代码如下:

r = requests.get(url)
if r.ok:
    soup = BeautifulSoup(r.content, 'lxml')
    soup.status_code
    j = json.loads(str(soup))

但出现了一个错误:

JSONDecodeError                           Traceback (most recent call last)
<ipython-input-2-b5e25d767a8a> in <module>
      4     soup = BeautifulSoup(r.content, 'lxml')
      5     soup.status_code
----> 6     j = json.loads(str(soup))

D:\Anaconda\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

D:\Anaconda\lib\json\decoder.py in decode(self, s, _w)
    335 
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

D:\Anaconda\lib\json\decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我检查了响应不是200,而是None

我怎样才能解决这个问题?多谢各位


Tags: andinselfnonejsonifparseis
1条回答
网友
1楼 · 发布于 2024-04-20 11:17:12

bs4用于解析HTML等

您应该首先使用r.contentsr.text检查响应类型和内容。如果什么都没有,那么你可能是打错了

如果您的文件是一个真正的JSON文件(特别是geojson),那么没有理由加载它,只需将其存储在文件或变量中即可。如果您正在使用类似folium的东西进行可视化项目,那么将有一个参数接受整个项目

例如,我几周前的一个项目中的代码:

folium.Choropleth(
    geo_data=r,
    data = df_filtered,
    key_on = 'feature.properties.ADMIN',
    columns=['Country','Skill Count'],
    fill_color='YlOrRd', 
    fill_opacity=0.7, 
    line_opacity=0.2,
    legend_name='Clash Royale "Skill" level',
    reset=True
).add_to(mapp)

相关问题 更多 >