2016-02-27 188 views
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' 
+0

您應該使用'如果dict'關鍵,以確保您有安全提取之前的數據。在你的情況下,'如果'estimatedResultCount'數據['光標']' – Obsidian

+0

你是主宰 – vandernath

回答

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"')