【问题标题】:bypass KeyError while searching results in Google在 Google 中搜索结果时绕过 KeyError
【发布时间】:2016-06-10 23:03:59
【问题描述】:

我有一个要使用 Google 验证其使用情况的关键字列表。例如,如果“free house”(带引号)在 Google 中返回结果,我会假设“free house”是常见用法。

问题是,如果 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' 

【问题讨论】:

  • 在安全提取数据之前,您应该使用if key in dict 确保您拥有数据。在你的情况下,if 'estimatedResultCount' in data['cursor']

标签: python api search search-engine urllib


【解决方案1】:

有几种方法可以处理错误。由于您在 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"')

【讨论】:

    猜你喜欢
    • 2011-03-27
    • 1970-01-01
    • 2015-12-18
    • 2018-11-24
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多