# Python Requests

把 helodata 接入 Python 爬虫最简洁的方式。

## 安装

```bash
pip install requests
# SOCKS5 支持：
pip install requests[socks]
```

## 住宅 / 移动（网关型）

```python
import requests

USER = "helo_s1a2b3c4d5e-type-res-region-us"      # 移动改成 type-mob
PASS = "PASSWORD"
proxy = f"http://{USER}:{PASS}@gate.helodata.io:7777"

r = requests.get(
    "https://ipv4.icanhazip.com",
    proxies={"http": proxy, "https": proxy},
    timeout=30,
)
print(r.text.strip())
```

## ISP

```python
PROXY = "http://helo_s1a2b3c4d5e:PASSWORD@198.51.100.42:8000"

r = requests.get(
    "https://ipv4.icanhazip.com",
    proxies={"http": PROXY, "https": PROXY},
    timeout=30,
)
```

## SOCKS5 + 远端 DNS

关键：使用 `socks5h://`（多一个 `h`）让代理解析 DNS——否则本地解析会泄露 DNS、地理失效。

```python
proxy = f"socks5h://{USER}:{PASS}@gate.helodata.io:7777"
```

## Session（HTTP keep-alive）

跨请求复用连接更快，尤其 ISP（IP 稳定）：

```python
s = requests.Session()
s.proxies = {"http": proxy, "https": proxy}

for url in urls:
    r = s.get(url, timeout=30)
```

## 住宅会话轮换

每批 N 个请求生成新的 `session-XXX`：

```python
import random, string

def make_user(country="us"):
    sid = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
    return f"helo_s1a2b3c4d5e-type-res-region-{country}-session-{sid}-sesstime-10"
```

## ISP 轮询

```python
import itertools
with open("isp.txt") as f:
    pool = itertools.cycle([l.strip() for l in f if l.strip()])

def fetch(url):
    ip, port, user, password = next(pool).split(":", 3)
    proxy = f"http://{user}:{password}@{ip}:{port}"
    return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=30)
```

生产级模式见 [客户端轮换](/helodata-zh/chan-pin/overview-2/rotation.md)。

## 重试

用 `urllib3.Retry` 处理瞬时错误：

```python
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=5, backoff_factor=0.5, status_forcelist=[429, 502, 522, 524])
s.mount("https://", HTTPAdapter(max_retries=retry))
```

## 验证

```python
r = s.get("https://ipv4.icanhazip.com")
print(r.text.strip(), r.headers.get("X-Helodata-Exit-IP"))
```

## 常见陷阱

* **proxies 字典少了 `https` 键** — 即便只访问 HTTPS 目标，Python `requests` 也要求 `http` 和 `https` 两个键都在。
* **写成 `socks5://` 而非 `socks5h://`** — DNS 泄露。SOCKS5 务必用 `socks5h://`。
* **未设超时** — 上游不稳时请求会无限挂起，**始终传 `timeout`**。


---

# 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/ji-cheng-zhi-nan/pa-chong-gong-ju/python-requests.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.
