快速开始

安装

环境要求

Python >= 3.10

# 核心安装(默认 httpx 引擎)
pip install hs-net

# 按需安装额外引擎
pip install hs-net[curl]         # curl-cffi(浏览器指纹模拟)
pip install hs-net[aiohttp]      # aiohttp
pip install hs-net[requests]     # requests
pip install hs-net[requests-go]  # requests-go
pip install hs-net[sp]           # 爬虫增强(CSS/XPath 选择器 + JMESPath + 随机 UA)
pip install hs-net[all]          # 全部引擎 + 爬虫增强

或使用其他包管理器:

# uv
uv add hs-net
uv add "hs-net[all]"    # 全部引擎

# poetry
poetry add hs-net
poetry add "hs-net[all]"

默认安装仅包含 httpx 引擎,其他引擎按需安装。引擎缺失时会抛出清晰的 EngineNotInstalled 异常并提示安装命令。

第一个请求

异步用法

async_example.py
import asyncio
from hs_net import Net

async def main():
    async with Net() as net:
        resp = await net.get("https://example.com")
        print(resp.status_code)  # 200
        print(resp.css("title::text").get())  # Example Domain

asyncio.run(main())

同步用法

sync_example.py
from hs_net import SyncNet

with SyncNet() as net:
    resp = net.get("https://example.com")
    print(resp.status_code)  # 200
    print(resp.css("title::text").get())  # Example Domain

快捷函数(最简用法)

无需实例化客户端,一行发起请求:

shortcuts.py
import hs_net

# 异步
resp = await hs_net.get("https://example.com")
print(resp.css("title::text").get())

# 同步
resp = hs_net.sync_get("https://example.com")
print(resp.text)
什么时候用快捷函数?

快捷函数每次创建临时客户端,适合简单的一次性请求。需要复用连接、配置中间件、控制并发时,请使用 Net / SyncNet

基本概念

Net vs SyncNet

NetSyncNet
调用方式await net.get()net.get()
上下文管理async withwith
可用引擎httpx, aiohttp, curl-cffi, requests-gohttpx, curl-cffi, requests, requests-go
适用场景高并发、异步框架脚本、同步框架

Response 对象

每次请求返回的 Response 对象包含:

resp = await net.get("https://example.com")

resp.status_code   # HTTP 状态码
resp.ok            # 是否 2xx
resp.text          # 响应文本
resp.content       # 原始字节
resp.json_data     # JSON 数据(自动解析)
resp.headers       # 响应头
resp.cookies       # 响应 cookies
resp.url           # 最终 URL(重定向后)
resp.domain        # 域名(含协议)
resp.host          # 主机名

配置优先级

参数覆盖遵循三级优先级:

请求方法参数  >  构造函数参数  >  NetConfig 默认值
priority.py
# NetConfig 设置 timeout=20(最低优先级)
config = NetConfig(timeout=20)

# 构造函数设置 timeout=10(中间优先级)
net = SyncNet(config=config, timeout=10)

# 请求方法设置 timeout=5(最高优先级)
resp = net.get("https://example.com", timeout=5)
# 实际超时: 5 秒