> For the complete documentation index, see [llms.txt](https://docs.ipwo.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ipwo.net/kai-fa-zhe-wen-dang/dai-ma-shi-li/python/aiohttp-yi-bu.md).

# aiohttp（异步）

使用 Python `aiohttp` 可以通过[ IPWO 代理](https://www.ipwo.net/)发起异步 HTTP 请求，适用于高并发数据采集与批量请求场景。

***

### 一、安装 aiohttp

```bash
pip install aiohttp
```

***

### 二、HTTP 代理示例

```python
import aiohttp
import asyncio

proxy = "http://username_custom_zone_US:password@us.ipwo.net:7878"

url = "http://ipinfo.io"

async def main():

    async with aiohttp.ClientSession() as session:

        async with session.get(
            url,
            proxy=proxy,
            timeout=30
        ) as response:

            print(await response.text())

asyncio.run(main())
```

***

### 三、正常返回示例

```json
{
  "ip": "203.0.113.10",
  "country": "US"
}
```

如果返回的 IP：

* 不是本机公网 IP
* 国家地区正确

说明代理已经生效。

***

### 四、高并发请求示例

```python
import aiohttp
import asyncio

proxy = "http://username_custom_zone_US:password@us.ipwo.net:7878"

urls = [
    "http://ipinfo.io",
    "http://api.ipify.org"
]

async def fetch(session, url):

    async with session.get(
        url,
        proxy=proxy,
        timeout=30
    ) as response:

        print(await response.text())

async def main():

    async with aiohttp.ClientSession() as session:

        tasks = [
            fetch(session, url)
            for url in urls
        ]

        await asyncio.gather(*tasks)

asyncio.run(main())
```

***

### 五、常见问题

#### [407 Proxy Authentication Required](/kai-fa-zhe-wen-dang/chang-jian-cuo-wu/407-proxy-authentication-required.md)

通常是：

* 用户名错误
* 密码错误
* zone 参数错误

***

#### [Timeout 超时](/kai-fa-zhe-wen-dang/chang-jian-cuo-wu/chao-shi-timeout.md)

通常是：

* 网络环境异常
* 并发过高
* DNS 问题

***

#### [Connection reset](/kai-fa-zhe-wen-dang/chang-jian-cuo-wu/connection-reset.md)

高并发场景可能出现：

```
连接被重置
```

建议：

* 增加 Retry
* 控制并发数量

***

### 六、推荐开发建议

推荐：

* 使用海外 VPS
* 控制并发数量
* 增加 timeout
* 增加 Retry 重试机制
* 使用粘性 Session

***

### 七、相关文章

* [Python Requests](/kai-fa-zhe-wen-dang/dai-ma-shi-li/python/requests.md)
* [HTTPX](/kai-fa-zhe-wen-dang/dai-ma-shi-li/python/httpx.md)
* [API 调用与批量采集](/dai-li-ji-chu-zhi-shi/api-diao-yong-yu-pi-liang-cai-ji.md)
* [超时 Timeout](/kai-fa-zhe-wen-dang/chang-jian-cuo-wu/chao-shi-timeout.md)
* [Connection reset](/kai-fa-zhe-wen-dang/chang-jian-cuo-wu/connection-reset.md)
* [什么是粘性会话](/dai-li-ji-chu-zhi-shi/shen-me-shi-nian-xing-hui-hua.md)
