0
我有一個關鍵字的列表,我想用它來驗證使用Google的使用情況。例如,如果「免費房子」(帶引號)在Google中返回結果,我會假設「免費房子」是常見用法。在Google搜索結果時繞過KeyError
問題是,如果在Google中沒有結果,我的代碼崩潰(KeyError)。我怎樣才能繞過這個錯誤?
(最後,如果Google沒有結果,我想從關鍵字列表中刪除關鍵字)。
這裏是我的代碼:
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'
您應該使用'如果dict'關鍵,以確保您有安全提取之前的數據。在你的情況下,'如果'estimatedResultCount'數據['光標']' – Obsidian
你是主宰 – vandernath