2016-08-12 74 views
0

的代碼非常簡單:蟒蛇功能,json.loads():無JSON對象可以解碼

import requests 
import json 

r = requests.get('https://www.baidu.com/') 
r.encoding = 'utf-8' 
json.loads(r.text,'utf-8') 

我總是收到此錯誤信息:

Traceback (most recent call last): 
File "<pyshell#57>", line 1, in <module> 
json.loads(r.text,'utf-8') 
File "C:\Python27\lib\json\__init__.py", line 352, in loads 
return cls(encoding=encoding, **kw).decode(s) 
File "C:\Python27\lib\json\decoder.py", line 364, in decode 
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode 
raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 

誰能幫助我解決這個問題?謝謝!

+4

這是因爲從'baidu.com'發送的響應不是JSON。在瀏覽器中打開「https:// www.baidu.com /」,看看你會得到什麼。 – ozgur

+0

謝謝,我從r.text得到的是' \ r \ n \ r \ n \ t \ r \ n \ r \ n \ r \ n \ t \ r \ n \ r \ n'。你知道有什麼問題嗎? – Yuandong

+0

你得到的是不能轉換爲JSON的東西。 – ozgur

回答

0

此代碼將幫助你弄清楚是怎麼回事;)

import requests 
import json 

r = requests.get('https://www.baidu.com/') 
r.encoding = 'utf-8' 

try: 
    foo = json.loads(r.text, 'utf-8') 
    print "Yay, I got a json from baidu!" 
except Exception, e: 
    print "Why didn't i get a json from baidu? Maybe it wasn't a json..." 
    print "What is it then? It seems is a {0} whose length is {1}".format(
     r.text.__class__, len(r.text) 
    ) 
+0

我跑你的代碼,並得到'它似乎是一個其長度爲227 – Yuandong

+0

r.text = u' \ r \ n \ r \ n \ t \ r \ n \ r \ n \ r \ n \ t \ r \ n \ r \ n' – Yuandong

+0

@Yuandong沒錯,那是我的觀點,正如你所看到的,這是一個包含HTML代碼的字符串,它不是JSON。這就是爲什麼你不能解碼它,你需要做一個請求返回一個JSON對象。 – BPL