【问题标题】:using try and except for searching urls using google api in python使用try,除了在python中使用google api搜索url
【发布时间】:2017-02-03 05:01:02
【问题描述】:

我想在一个列表中搜索 url,总共有大约 74 个 url。我使用 try 和 except 来告诉 python 跳过不响应的站点(带有 http 错误代码 400 等)

from googleapiclient.discovery import build
service = build("customsearch", "v1", developerKey='keyhere')

for i in range(0,k-1):
    try:
        queries = search_sources[i]
        res = service.cse().list(q= queries, cx='idhere',).execute()
    except urllib2.HTTPError:
        continue

但问题是我收到有关某些网站有错误的消息(这意味着除了部分不起作用):

   Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/googleapiclient/http.py", line 838, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/customsearch/v1?q=site%3Ahttp%3A%2F%2Fbit.ly%2FgktvnmChina+protest&alt=json&cx=myid&key=mykey returned "Bad Request">

【问题讨论】:

  • 尝试更通用的except 行。例如except Exception:.
  • @SonofaBeach 刚刚发布了整个错误
  • 它说 googleapiclient.errors.HttpError 所以在 except 中使用它
  • 你应该只做for queries in search_sources:而不是手动操作i作为索引。

标签: python google-api except


【解决方案1】:

您需要捕获正确的 HttpError。读取轨迹。

googleapiclient.errors.HttpError:

所以导入那个

from googleapiclient.errors import HttpError as GoogleHttpError

然后

except GoogleHttpError:

【讨论】:

  • 谢谢。代码有效,但我没有得到任何资源?
  • 我只是在回答提问的问题。不知道该库是如何工作的,但看起来您没有使用或检查循环中的 res 值
【解决方案2】:

根据您的异常输出中的raise 行,我认为您想要的异常处理程序是:

except HttpError:
    continue

编辑:您需要导入此异常,类似于@cricket_007 答案。

或者只使用泛型:

except Exception:
    continue

【讨论】:

  • 我得到“HttpError”未定义
  • 对于那个,代码有效,但我没有得到任何 res 的结果
  • 你的意思是当有异常时,或者没有异常时,你没有得到res 值?当出现异常时,您当然不应该得到res
  • 是的,这很奇怪。我做了 res 并收到消息 >>> res Traceback(最近一次调用最后一次):文件“”,第 1 行,在 NameError: name 'res' is not defined
  • 您需要发布您在哪里使用res 的代码。它是否超出范围(因此未定义)?另请参阅:stackoverflow.com/questions/25666853/…
猜你喜欢
  • 2012-09-03
  • 2016-05-09
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
相关资源
最近更新 更多