概述

CFspider 提供完整的异步 HTTP 请求功能,基于 httpx 实现,支持 HTTP/2 协议和流式响应,适合高并发场景。

性能优势

异步请求可以同时处理大量请求,性能远高于同步请求。例如:同步请求 10 个 URL 需要约 10 秒(串行),异步请求只需要约 1 秒(并发)。

安装依赖

使用异步功能需要安装 httpx:

bash
pip install httpx[http2]

cfspider.aget()

异步 GET 请求。

函数签名

python
await cfspider.aget(
    url: str,
    cf_proxies: str = None,
    cf_workers: bool = True,
    http2: bool = True,
    token: str = None,
    **kwargs
) -> AsyncCFSpiderResponse

参数说明

参数与同步 get() 相同,但默认启用 http2=True

使用示例

python
import asyncio
import cfspider

async def main():
    response = await cfspider.aget("https://httpbin.org/ip")
    print(response.json())
    print(response.http_version)  # HTTP/2

asyncio.run(main())

并发请求

python
import asyncio
import cfspider

async def main():
    urls = [
        "https://httpbin.org/ip",
        "https://httpbin.org/user-agent",
        "https://httpbin.org/headers"
    ]
    
    # 并发请求
    tasks = [cfspider.aget(url) for url in urls]
    responses = await asyncio.gather(*tasks)
    
    for response in responses:
        print(response.json())

asyncio.run(main())

其他异步方法

CFspider 提供所有 HTTP 方法的异步版本:

流式响应

使用 astream() 处理大文件下载。

python
import asyncio
import cfspider

async def main():
    async with cfspider.astream("GET", "https://example.com/large-file") as response:
        async for chunk in response.aiter_bytes():
            # 处理数据块
            process(chunk)

asyncio.run(main())