首页 > 解决方案 > aiohttp客户端连接错误,但是我可以在网上找到网站就好了?

问题描述

我正在尝试使用我在网上找到的此代码从 url 列表中异步返回 HTTP 请求代码,但是在打印了几次后,我收到错误 ClientConnectorError: Cannot connect to host website_i_removed :80 ssl:None [getaddrinfo failed]。由于该网站是有效的,我对它如何说我无法连接感到困惑。如果我在任何时候做错了,请指出我正确的方向。

在过去的几个小时里,我一直在查看 aiohttp 的文档和在线信息,但是他们没有关于带有 url 列表的 HTTP 请求的示例,而且他们在文档中的入门页面很难理解,因为我是新手异步编程。下面是我正在使用的代码,假设 urls 是一个字符串列表。

import asyncio
from aiohttp import ClientSession

async def fetch(url, session):
async with session.get(url) as response:
    code_status = response.history[0].status if response.history else response.status
    print('%s -> Status Code: %s' % (url, code_status))
    return await response.read()


async def bound_fetch(semaphore, url, session):
# Getter function with semaphore.
async with semaphore:
    await fetch(url, session)


async def run(urls):
tasks = []
# create instance of Semaphore
semaphore = asyncio.Semaphore(1000)

async with ClientSession() as session:
    for url in urls:
        # pass Semaphore and session to every GET request
        task = asyncio.ensure_future(bound_fetch(semaphore, url, session))
        tasks.append(task)

    responses = asyncio.gather(*tasks)
    await responses

loop = asyncio.get_event_loop()

future = asyncio.ensure_future(run(urls))
loop.run_until_complete(future)

我希望每个网站都打印其请求代码以确定它们是否可以访问,但是它说我无法连接到某些网站,尽管我可以在浏览器中查找它们。

标签: pythonasynchronousaiohttp

解决方案


推荐阅读