使用try和除了在python中使用google api搜索url

时间:2017-02-03 05:01:02

标签: python google-api except

我想在列表中搜索网址,最多可添加约74个网址。我使用try和except来告诉没有响应的python skip站点(使用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">

2 个答案:

答案 0 :(得分:2)

您需要捕获正确的HttpError。阅读踪迹。

googleapiclient.errors.HttpError:

所以导入

from googleapiclient.errors import HttpError as GoogleHttpError

然后

except GoogleHttpError:

答案 1 :(得分:0)

根据异常输出中的 @logName class Person { @logName firstname="Someone"; @logName fullName() { return this.firstname+' '+this.lastname; } } 行,我认为你想要的异常处理程序是:

raise

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

或者只使用通用:

except HttpError:
    continue