# 会话与轮换

「会话」是让多次请求保持同一住宅出口 IP 的机制。helodata 支持两种模式，**按请求**通过用户名指定。

## 轮换模式（默认）

省略 `session` 与 `sesstime` 段。每个新 TCP 连接都从匹配 IP 池中重新挑选。

```
helo_s1a2b3c4d5e-type-res-region-us
```

适用场景：

* 不需要保留 cookie 的单次抓取
* 通过 IP 多样性绕过反爬
* 大规模并行爬取，追求 IP 池最大多样性

注意：单客户端中的 keep-alive 连接复用可能在连接关闭前都使用同一 IP。如果需要严格的「每请求一新 IP」，请强制新建连接（`Connection: close`）。

## 粘性模式

同时追加 `session-{id}` 与 `sesstime-{分钟}`。**完整用户名字符串相同**的请求会复用同一出口 IP，最长 `sesstime` 分钟。

```
helo_s1a2b3c4d5e-type-res-region-us-session-job1-sesstime-30
```

| 约束                | 值                           |
| ----------------- | --------------------------- |
| `sesstime` 上限（住宅） | 30 分钟                       |
| 会话 ID 字符集         | `[a-z0-9]`，最多 32 字符         |
| IP 保证             | best-effort——上游 IP 掉线可能重新分配 |
| 会话计时              | 首次请求触发                      |

适用场景：

* 多步骤流程（登录 → 搜索 → 下单）
* 反爬信号会在几分钟内绑定 IP 的站点
* 需要响应可复现的测试

## 粘性下的并发

`session_id` 相同但**其他参数不同**（不同地理、不同子账号）的两次请求被视为**不同会话**。**完整用户名**才是会话键，不仅仅是 ID。

例如：

```
helo_s1a2b3c4d5e-type-res-region-us-session-abc-sesstime-30
helo_s1a2b3c4d5e-type-res-region-de-session-abc-sesstime-30
```

会开两个独立会话，一个落在美国，一个落在德国。

## 会话掉线恢复

若上游 IP 中途掉线，使用同一用户名的下一次请求会拿到新 IP 并重置计时。响应头会标记：

```
X-Helodata-Session-Repinned: true
```

长流程中要监测这个头，出现时考虑重置客户端状态（cookie、指纹）。

## 用法示例

### N 个并发粘性会话池

```python
import requests, random, string

BASE = "helo_s1a2b3c4d5e-type-res-region-us"

def session_user(n):
    sid = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
    return f"{BASE}-session-{sid}-sesstime-10"

users = [session_user(i) for i in range(20)]      # 20 个粘性会话

def get(url, user):
    proxy = f"http://{user}:PASSWORD@gate.helodata.io:7777"
    return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=30)
```

把 `users` 按轮询分给工作线程即可。

### 用完即弃

追踪每个会话的失败次数。超过阈值（如 60 秒内 3 次失败）即抛弃该会话 ID，生成新 ID。

## 会话**不会**做的事

* 不会延长流量额度——带宽依然按字节扣费
* 不会自动维持 cookie、请求头、TLS 指纹——这是客户端的工作
* 不保证某个特定 IP——只保证窗口期内 IP **稳定**

## 相关

* [ASN 定位](/helodata-zh/chan-pin/overview/asn-targeting.md) — 结合会话可在整个流程中锁定同一 ISP
* [国家与城市](/helodata-zh/chan-pin/overview/locations.md) — 地理字段必须一致才能共享会话
* [407 错误](/helodata-zh/gu-zhang-pai-cha/407.md) — 会话语法错误时常见


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.helodata.com/helodata-zh/chan-pin/overview/sessions-and-rotation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
