【问题标题】:JSONDecodeError: Expecting value: line 1 column 1 (char 0) at line response.json()JSONDecodeError:期望值:第 1 行第 1 列(字符 0)在第 response.json() 行
【发布时间】:2018-08-04 13:14:43
【问题描述】:

我收到错误 Expecting value: line 1 column 1 (char 0) on the line response.json()。

我尝试了什么

与其他答案相反,我在 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)

【问题讨论】:

    标签: json python-3.x python-requests


    【解决方案1】:

    函数response.json() 尝试解码作为请求响应发送的任何 JSON。但显然,https://www.google.com 不返回 json;它以 html 响应。

    这从response.text 中很明显,它将返回的 html 显示为字符串。

    如果您使用响应实际 JSON 的 url,例如 https://jsonplaceholder.typicode.com/todos/1,那么您将不会收到任何错误。

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 2019-02-25
      • 2018-06-28
      • 2018-08-28
      • 2020-10-10
      • 1970-01-01
      • 2019-07-04
      • 2020-02-03
      相关资源
      最近更新 更多