python 3.5 asyncio 和 aiohttp Errno 101 网络不可达

python 3.5 asyncio and aiohttp Errno 101 Network is unreachable

我在 Ubuntu 16.

上使用 python 3.5

我正在尝试使用 aiohttp 编写一个简单的客户端。

这是我的代码。我从 here 拿来的。这是第一个代码示例,禁用了 ssl 检查:

import aiohttp
import asyncio
import async_timeout

async def fetch(session, url):
    with async_timeout.timeout(10):
        async with session.get(url) as response:
            return await response.text()

async def main(loop):
    conn = aiohttp.TCPConnector(verify_ssl=False)
    async with aiohttp.ClientSession(loop=loop, connector=conn) as session:
        html = await fetch(session, 'http://www.google.com')
        print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))

对于某些网站,此代码有效。对于其他人,包括 http://python.orghttp://google.com,它不起作用。相反,代码会生成此错误:

aiohttp.errors.ClientOSError: [Errno 101] Cannot connect to host google.com:80 ssl:False [Can not connect to google.com:80 [Network is unreachable]]

我尝试了一个简单的 requests 脚本,像这样:

import requests
rsp = requests.get('http://google.com')
print(rsp.text)

这有效,我可以达到 google。 curl和wget也达到了google.

在做一些研究时,我遇到了一个不同的问题。这个问题和我自己的很相似。我找到了 。我尝试了此处提供的解决方案,但仍然无效。

并非所有站点都会出现此问题。我遇到了有效和无效的 http 和 https 网站。

关于为什么会发生这种情况以及如何解决这个问题有什么建议吗?

谢谢!

备注:

我试过的其他东西。

  1. 添加我自己的 DNS 解析器,也使用 aiohttp。
  2. 使用 https 版本的网站,得到同样的错误。
  3. 稍微不同 url,例如 https://www.google.com/?#q=python

我在使用 AsyncResolver 作为连接的解析器时遇到了类似的问题。它曾经是默认的解析器,因此可能会因您而异。该问题与 ipv6 域有关,其中 AsyncResolver 有问题,因此解决方案是简单地将系列指定为 ipv4 地址

conn = aiohttp.TCPConnector(
        family=socket.AF_INET,
        verify_ssl=False,
    )