> For the complete documentation index, see [llms.txt](https://docs.ipdunar.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ipdunar.com/zh/ji-cheng-zhi-nan/pa-chong-gong-ju/python-requests.md).

# Python Requests

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

## 安装

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

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

```python
import requests

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

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

## ISP

```python
PROXY = "http://ipdunar_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.ipdunar.com: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"ipdunar_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)
```

生产级模式见 [客户端轮换](https://docs.ipdunar.com/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-Ipdunar-Exit-IP"))
```

## 常见陷阱

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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.ipdunar.com/zh/ji-cheng-zhi-nan/pa-chong-gong-ju/python-requests.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
