我有一个关键字列表,我想使用Google验证其使用情况。例如,如果“免费住宅”(带引号)在Google中返回结果,我会认为“免费住房”是常用的。
问题是,如果谷歌没有结果,我的代码崩溃了(KeyError)。如何绕过此错误?
(最后,如果谷歌没有结果,我想从我的关键字列表中删除该关键字。)
这是我的代码:
import json
import urllib
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_results)
data = results['responseData']
print 'Total results: %s' % data['cursor']['estimatedResultCount']
hits = data['results']
print 'Top %d hits:' % len(hits)
for h in hits: print ' ', h['url']
print 'For more results, see %s' % data['cursor']['moreResultsUrl']
showsome('"this is not searched searched in Google"')
和追溯:
KeyError Traceback (most recent call last)
c:\users\nathan\appdata\local\temp\tmpuj7hhu.py in <module>()
15 print 'For more results, see %s' % data['cursor']['moreResultsUrl']
16
---> 17 showsome('"this is not searched searched in Google"')
c:\users\nathan\appdata\local\temp\tmpuj7hhu.py in showsome(searchfor)
9 results = json.loads(search_results)
10 data = results['responseData']
---> 11 print 'Total results: %s' % data['cursor']['estimatedResultCount']
12 hits = data['results']
13 print 'Top %d hits:' % len(hits)
KeyError: 'estimatedResultCount'
答案 0 :(得分:0)
有两种方法可以处理错误。由于您在dict
中进行多次查找,因此将其全部包含在try/except
块中是一个不错的选择
import json
import urllib
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_results)
try:
data = results['responseData']
print 'Total results: %s' % data['cursor']['estimatedResultCount']
hits = data['results']
print 'Top %d hits:' % len(hits)
for h in hits: print ' ', h['url']
print 'For more results, see %s' % data['cursor']['moreResultsUrl']
except KeyError:
print "I'm gettin' nuth'in man"
showsome('"this is not searched searched in Google"')