python爬虫报错raise JSONDecodeError("Expecting value", s, err.value)

python爬虫报错raise JSONDecodeError("Expecting value", s, err.value)

初学爬虫,准备跟着教程爬取一个知乎用户的粉丝列表。代码完全按照教程来的,最后却报错了,希望各位指点迷津

import requests

url='https://www.zhihu.com/api/v4/members/ou-zhou-jin-xue-zu-qiu-shi-ren/followers?include=data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F%28type%3Dbest_answerer%29%5D.topics&offset=0&limit=20'

req=requests.get(url,headers=UA) #headers太长我就没放出来,对着知乎请求头复制粘贴的应该不会有问题吧

'''

req.encoding=req.apparent_encoding

我在搜索解决方法时看见有人说用这种方法可以解决我的问题,但加入这行后还是没用

'''

print(req.status_code) #状态码是200

print(req.json())

希望各位能告诉我为何req.json()无法打印

代码报错的完整内容如下

Traceback (most recent call last):

File "D:\study_documents\python\codes\zhihu_followers_spider\main.py", line 21, in <module>

print(req.json())

File "C:\Users\朗风\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 900, in json

return complexjson.loads(self.text, **kwargs)

File "C:\Users\朗风\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads

return _default_decoder.decode(s)

File "C:\Users\朗风\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode

obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "C:\Users\朗风\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode

raise JSONDecodeError("Expecting value", s, err.value) from None

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我在站内搜索过,但没找到因为爬虫引起的相关问题,也可能是我搜索方式有问题,如果您能给我相关问题的解答的话,我将感激不尽。


回答:

這説明返回的内容不是 JSON 格式的。改成這樣看看:

print(req.text)


回答:

事实上正是我忽视的headers里出了问题...
headers本来的部分内容是这样的
'accept-encoding': 'gzip, deflate,br'`
参考http://www.qishunwang.net/new...后,我删除了br,然后json就可以正常打印了

以上是 python爬虫报错raise JSONDecodeError(&quot;Expecting value&quot;, s, err.value) 的全部内容, 来源链接: utcz.com/p/938070.html

回到顶部