python - 从未检索到 future 的异常

标签 python exception python-asyncio coroutine 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
    ...

当它尝试向格式错误的 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

尝试从 session.get 产生响应时发生错误。据我了解,异常从未被 asyncio 消耗过,因此它不是“喋喋不休”。

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

try:
    response = yield from self.session.get(url, headers=self.headers)
except Exception:
    return None

这行不通。

然后我read here关于链接协程以捕获异常,但这对我也不起作用。一定时间后我仍然收到这些消息和脚本崩溃。

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

最佳答案

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

我会在请求之前验证 URL。尝试收集一些数据时,我对这类东西感到很头疼,所以我决定提前修复它们,并将格式错误的 URL 报告到日志中。

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

在这个问题中,有人给出了 django 的验证正则表达式。 Python - How to validate a url in python ? (Malformed or not)

关于python - 从未检索到 future 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41142421/

相关文章:

带有 aioboto3 的 Python 3 asyncio 似乎是连续的

python-asyncio - future.add_done_callback() 的用例是什么?

python - Django休息框架: other URLs overwritten when including default router

java - junit 测试 - assertEquals 异常

c# - Linq、XmlNodes、foreach 和异常

javascript异常对象格式

python - 在事件流之外运行 asyncio 协程

python - 如何使用 pandas 从内部联接获取索引对而不创建结果数据框?

python - 无法从 secure_filename(f.filename) 读取文件

python - MSSQL 'Numeric Value Out of Range' 20 位 python Long Int 到 Numeric(24,0) 列时出错