从未检索到未来的异常

Cha*_*nel 6 python exception-handling coroutine python-asyncio aiohttp

我有一个抓取工具(基于 Python 3.4.2 和 asyncio/aiohttp 库)和一堆链接(> 10K)来检索一些少量数据。部分爬虫代码:

@asyncio.coroutine
def prepare(self, links):
    semaphore = asyncio.Semaphore(self.limit_concurrent)
    tasks = []
    result = []

    tasks = [self.request_data(link, semaphore) for link in links]

    for task in asyncio.as_completed(tasks):
        response = yield from task
        if response:
            result.append(response)
        task.close()
    return result

@asyncio.coroutine
def request_data(self, link, semaphore):

    ...

    with (yield from semaphore):
        while True:
            counter += 1
            if counter >= self.retry:
                break
            with aiohttp.Timeout(self.timeout):
                try:
                    response = yield from self.session.get(url, headers=self.headers)
                    body = yield from response.read()
                    break
                except asyncio.TimeoutError as err:
                    logging.warning('Timeout error getting {0}'.format(url))
                    return None
                except Exception:
                    return None
    ...
Run Code Online (Sandbox Code Playgroud)

当它尝试向格式错误的 URL 发出请求时,我收到如下消息:

Future exception was never retrieved
future: <Future finished exception=gaierror(11004, 'getaddrinfo failed')>
Traceback (most recent call last):
  File "H:\Python_3_4_2\lib\concurrent\futures\thread.py", line 54, in run
    result = self.fn(*self.args, **self.kwargs)
  File "H:\Python_3_4_2\lib\socket.py", line 530, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed
Run Code Online (Sandbox Code Playgroud)

尝试从 session.get 产生响应时发生错误。据我所知,异常从未被 asyncio 消耗过,所以它不是“胡言乱语”。

首先,我尝试通过 try/except 简单地包装请求:

try:
    response = yield from self.session.get(url, headers=self.headers)
except Exception:
    return None
Run Code Online (Sandbox Code Playgroud)

这不起作用。

然后我在这里阅读了关于链接协程以捕获异常的内容,但这对我也不起作用。在一段时间后,我仍然收到这些消息和脚本崩溃。

所以我的问题 - 我如何以正确的方式处理这个异常?

小智 3

不是您问题的答案,但也许是您问题的解决方案,具体取决于您是否只想让代码正常工作。

我会在请求 URL 之前验证它们。我在尝试收集一些数据时遇到了很多麻烦,因此我决定预先修复它们,并将格式错误的网址报告到日志中。

您可以使用 django 的正则表达式或其他代码来执行此操作,因为它是公开可用的。

在这个问题中,一个人给出了 django 的验证正则表达式。 Python - 如何在 python 中验证 url?(畸形与否)