我有这段代码可以使用google API在google中搜索一个单词,但是有一次它可以正常工作,但是如果我添加了很多单词或者如果我运行了很多次,我会不断出现以下错误...
results = jsonResponse['responseData']['results']
TypeError: 'NoneType' object has no attribute '__getitem__'
我试图在Google上搜索很多,但无法知道问题是什么..任何人都可以帮助我知道问题和如何处理...苦于此错误
import urllib
import urllib2
from urllib import urlencode
import json as m_json
from urllib2 import urlopen
import re
import json
from nltk.corpus import stopwords
import sys
from urllib2 import urlopen
import urllib2
import simplejson
import pprint
words = ['headache','diabetes','myopia','dhaed','snow','blindness','head','ache','acne','aids','blindness','head','ache','acne','aids','blindness','head','ache','acne','aids']
for word in words:
url = ('https://ajax.googleapis.com/ajax/services/search/web'
'?v=1.0&q='+word+'&userip=192.168.1.105')
request = urllib2.Request(url)
response = urllib2.urlopen(request)
jsonResponse=json.loads(response.read())
#print "the response now is: ",jsonResponse
#pprint.pprint(jsonResponse)
results = jsonResponse['responseData']['results']
for result in results:
print "\nthe result is: ",result
url =result['url']
print "\nthe url is: ",url
try:
page=urllib2.urlopen(url).read()
except urllib2.HTTPError,err:
if err.code == 403:
print "bad"
continue
else:
print "good"
break
except urllib2.HTTPError:
print "server error"
except:
print "dont know the error"
谢谢是提前..
最佳答案
可能是当没有结果时,jsonResponse['responseData']
是None
,因此它在结果中没有名为results
的属性,或者responseData
本身是None
(== JSON null
)。 (对于jsonResponse
或jsonResponse['responseData']
为空/无,字典查找失败。
当该错误发生时转储输出以查看哪个是None
,然后在results = jsonResponse['responseData']['results']
行之前对其进行检查。