我遇到错误期望值:response.json()行上的第1行第1列(字符0)。
我尝试的内容
相对于其他答案,我在json.loads()处没有收到错误,但在response.json()处却没有错误。我也尝试过调整响应数据主体,但没有帮助,这里是代码。
import requests
import json
from bs4 import BeautifulSoup as Soup
def get_links(search_name):
search_name = search_name.replace(' ', '+')
response = requests.get("http://www.google.com/search",
params={'q': search_name, 'first': 0},
headers={'User-Agent': user_agent})
dataform = response.json()
page = json.loads(dataform)
new_soup = Soup(page[1][1], 'lxml')
images = new_soup.find_all('img')
links = [image['src'] for image in images]
return links
回溯:
<ipython-input-27-8d351939888e> in get_links(search_name)
17 params={'q': search_name, 'first': 0},
18 headers={'User-Agent': user_agent})
---> 19 dataform = response.json()
20 page = json.loads(dataform)
21 new_soup = Soup(page[1][1], 'lxml')
/usr/local/lib/python3.6/dist-packages/requests/models.py in json(self, **kwargs)
890 # used.
891 pass
--> 892 return complexjson.loads(self.text, **kwargs)
893
894 @property
/usr/lib/python3.6/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
352 parse_int is None and parse_float is None and
353 parse_constant is None and object_pairs_hook is None and not kw):
--> 354 return _default_decoder.decode(s)
355 if cls is None:
356 cls = JSONDecoder
/usr/lib/python3.6/json/decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):
/usr/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
答案 0 :(得分:2)
函数response.json()
尝试解码作为请求响应发送的任何JSON。但显然, https://www.google.com 不会返回json;它以html代替。
这在response.text
中很明显,它以字符串形式显示了返回的html。
如果您使用一个以实际JSON响应的URL,例如 https://jsonplaceholder.typicode.com/todos/1 ,那么您将不会收到任何错误。