2016-03-03 106 views
-1

我試圖發送一個http請求到任何url,並使用urllib庫得到響應。以下是我使用的代碼:simplejson.scanner.JSONDecodeError:期望值:第1行第3列(char 2)

>>> import requests 
>>> r = requests.get("http://www.youtube.com/results?bad+blood") 
>>> r.status_code 
    200 

當我嘗試這樣做時出現以下錯誤。

>>> r.json() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Library/Python/2.7/site-packages/requests/models.py", line 808, in json 
    return complexjson.loads(self.text, **kwargs) 
    File "/Library/Python/2.7/site-packages/simplejson/__init__.py", line 516, in loads 
    return _default_decoder.decode(s) 
    File "/Library/Python/2.7/site-packages/simplejson/decoder.py", line 370, in decode 
    obj, end = self.raw_decode(s) 
    File "/Library/Python/2.7/site-packages/simplejson/decoder.py", line 400, in raw_decode 
    return self.scan_once(s, idx=_w(s, idx).end()) 
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 3 (char 2) 

有人能告訴我最新代碼有什麼問題。

PS:我使用python 2.7.10

回答

1

該URL返回HTML,而不是JSON,所以沒有點呼籲的響應.json()

2

響應不是JSON,它是'text/html; charset=utf-8'。如果你想解析它,請使用類似BeautifulSoup的東西。

>>> import requests, bs4 
>>> rsp = requests.get('http://www.youtube.com/results?bad+blood') 
>>> rsp.headers['Content-Type'] 
'text/html; charset=utf-8' 
>>> soup = bs4.BeautifulSoup(rsp.content, 'html.parser') 

我推薦使用YouTube搜索API。登錄Google Developers Console,設立繼API Key Setup instructions一個API密鑰,那麼你可以使用YouTube Search API發出請求:

>>> from urllib import parse 
>>> import requests 
>>> query = parse.urlencode({'q': 'bad blood', 
...       'part': 'snippet', 
...       'key': 'OKdE7HRNPP_CzHiuuv8FqkaJhPI2MlO8Nns9vuM'}) 
>>> url = parse.urlunsplit(('https', 'www.googleapis.com', 
...       '/youtube/v3/search', query, None)) 
>>> rsp = requests.get(url, headers={'Accept': 'application/json'}) 
>>> rsp.raise_for_status() 
>>> response = rsp.json() 
>>> response.keys() 
dict_keys(['pageInfo', 'nextPageToken', 'regionCode', 'etag', 'items', 'kind']) 

請注意,如果你想使用Python 2的例子中,使用Python 3,那你將不得不從urlparseurlliburlunsplit導入urlencode

相關問題