# requests.exceptions.TooManyRedirects: 在获取'https://redirect.example.com'时超过30次重定向

- **ID:** `python/requests-connectionerror-too-many-redirects`
- **领域:** python
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

服务器在循环中重定向客户端或重定向次数过多。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Manually handle redirects by inspecting the Location header** (85% 成功率)
   ```
   response = requests.get('https://redirect.example.com', allow_redirects=False)
while response.is_redirect:
    next_url = response.headers['Location']
    response = requests.get(next_url, allow_redirects=False)
    if response.status_code == 200:
        break
   ```
2. **Use a session with a custom redirect handler to detect loops** (80% 成功率)
   ```
   from requests import Session
s = Session()
s.max_redirects = 10
response = s.get('https://redirect.example.com')
   ```

## 无效尝试

- **Disabling redirects entirely** — May miss the final target if redirects are legitimate. (70% 失败率)
- **Increasing the maximum redirect limit arbitrarily** — If it's a loop, increasing limit does not help; it will still exceed. (80% 失败率)
