由 Zied Boughdir 增强
所有功能均已测试,核心功能 100% 成功率:
这是一个用于绕过 Cloudflare 反机器人页面(也称为“I'm Under Attack Mode”,即 IUAM)的 Python 模块,基于 Requests 实现。该增强版支持 Cloudflare v2 挑战、代理轮换、隐身模式等功能。Cloudflare 会定期更改其技术,因此我会经常更新此仓库。
如果你希望抓取或爬取受 Cloudflare 保护的网站,这会非常有用。Cloudflare 的反机器人页面目前仅检查客户端是否支持 Javascript,不过未来他们可能会增加其他技术。
由于 Cloudflare 不断更改并强化其防护页面,cloudscraper 需要 JavaScript 引擎/解释器来解决 Javascript 挑战。这样脚本就能轻松模拟普通网络浏览器,而无需显式反混淆和解析 Cloudflare 的 Javascript。
作为参考,以下是 Cloudflare 用于此类页面的默认消息:``` Checking your browser before accessing website.com.
This process is automatic. Your browser will redirect to your requested content shortly.
Please allow up to 5 seconds...
任何使用 cloudscraper 的脚本在首次访问启用了 Cloudflare 反机器人机制的网站时都会休眠约 5 秒,不过首次请求之后不会再有任何延迟。
# 安装
只需运行 `pip install cloudscraper` 即可。PyPI 包位于 https://pypi.org/project/cloudscraper/```bash
pip install cloudscraper
或者,克隆此仓库并运行 python setup.py install。
如果您之前使用的是原版 cloudscraper 包,现在可以直接使用此增强版本:```python
import cloudscraper # Enhanced version
The API remains compatible, so you only need to change the import statements in your code. All function calls and parameters work the same way.
### Codebase Structure
The codebase has been streamlined to improve maintainability and reduce confusion:
- **Single Module**: All code is now in the `cloudscraper` module
- **Removed Redundancy**: The redundant directories have been removed
- **Updated Tests**: All test files have been updated to use the `cloudscraper` module
This makes the codebase cleaner and easier to maintain while ensuring backward compatibility with existing code that uses the original API.
## Key Features in cloudscraper
| Feature | Description | Status |
|---------|-------------|--------|
| **🆕 Executable Compatibility** | Complete fix for PyInstaller, cx_Freeze, auto-py-to-exe conversion | ✅ **FIXED** |
| **🆕 v3 JavaScript VM Challenges** | Support for Cloudflare's latest JavaScript VM-based challenges | ✅ **NEW** |
| **🆕 Turnstile Support** | Support for Cloudflare's new Turnstile CAPTCHA replacement | ✅ **NEW** |
| **Modern Challenge Support** | Enhanced support for v1, v2, v3, and Turnstile Cloudflare challenges | ✅ Complete |
| **Proxy Rotation** | Built-in smart proxy rotation with multiple strategies | ✅ Enhanced |
| **Stealth Mode** | Human-like behavior simulation to avoid detection | ✅ Enhanced |
| **Browser Emulation** | Advanced browser fingerprinting for Chrome and Firefox | ✅ Stable |
| **JavaScript Handling** | Better JS interpreter (js2py as default) for challenge solving | ✅ Enhanced |
| **Captcha Solvers** | Support for multiple CAPTCHA solving services | ✅ Stable |
# Dependencies
- **Python 3.8+** (Dropped support for Python 3.6 and 3.7)
- **[Requests](https://github.com/psf/requests)** >= 2.31.0
- **[requests_toolbelt](https://pypi.org/project/requests-toolbelt/)** >= 1.0.0
- **[pyparsing](https://pypi.org/project/pyparsing/)** >= 3.1.0
- **[pyOpenSSL](https://pypi.org/project/pyOpenSSL/)** >= 24.0.0
- **[pycryptodome](https://pypi.org/project/pycryptodome/)** >= 3.20.0
- **[websocket-client](https://pypi.org/project/websocket-client/)** >= 1.7.0
- **[js2py](https://pypi.org/project/Js2Py/)** >= 0.74
- **[brotli](https://pypi.org/project/Brotli/)** >= 1.1.0
- **[certifi](https://pypi.org/project/certifi/)** >= 2024.2.2
`python setup.py install` will install the Python dependencies automatically. The javascript interpreters and/or engines you decide to use are the only things you need to install yourself, excluding js2py which is part of the requirements as the default.
# Javascript Interpreters and Engines
We support the following Javascript interpreters/engines.
- **[ChakraCore](https://github.com/microsoft/ChakraCore):** Library binaries can also be located [here](https://www.github.com/VeNoMouS/cloudscraper/tree/ChakraCore/).
- **[js2py](https://github.com/PiotrDabkowski/Js2Py):** >=0.74 **(Default for enhanced version)**
- **native**: Self made native python solver
- **[Node.js](https://nodejs.org/)**
- **[V8](https://github.com/sony/v8eval/):** We use Sony's [v8eval](https://v8.dev)() python module.
# Usage
The simplest way to use cloudscraper is by calling `create_scraper()`.```python
import cloudscraper
scraper = cloudscraper.create_scraper() # returns a CloudScraper instance
# Or: scraper = cloudscraper.CloudScraper() # CloudScraper inherits from requests.Session
print(scraper.get("http://somesite.com").text) # => "<!DOCTYPE html><html><head>..."
就这样...
从此会话对象发往受 Cloudflare 反机器人保护网站的请求都将被自动处理。未使用 Cloudflare 的网站将按正常方式处理。你无需额外配置或调用任何内容,实际上可以将所有网站都视为不受任何保护。
你使用 cloudscraper 的方式与使用 Requests 完全相同。cloudScraper 的工作方式与 Requests Session 对象一致,区别仅在于不是调用 requests.get() 或 requests.post(),而是调用 scraper.get() 或 scraper.post()。
如需了解更多信息,请参阅 Requests 的文档。
使用 cloudscraper 将 Python 应用程序转换为可执行文件时遇到的用户代理问题已完全修复!
在将 Python 应用转换为可执行文件(使用 PyInstaller、cx_Freeze、auto-py-to-exe 等)时,由于 browsers.json 文件未被正确包含,用户会遇到与 用户代理 或 agent_user 功能相关的错误。
cloudscraper v2.7.0 包含一个自动回退系统:
选项 1:直接构建你的可执行文件(自动生效):```bash pyinstaller your_app.py
**选项 2:包含完整的用户代理数据库**(推荐):```bash
pyinstaller --add-data "cloudscraper/user_agent/browsers.json;cloudscraper/user_agent/" your_app.py
所有可执行兼容性均已经过全面测试:``` ✅ Normal operation with browsers.json ✅ Fallback operation without browsers.json ✅ PyInstaller environment simulation ✅ All browser/platform combinations ✅ HTTP requests with fallback user agents
您的 cloudscraper 应用程序在转换为可执行文件后将完美运行!🎉
## 🆕 Cloudflare v3 JavaScript VM 挑战支持
### 什么是 v3 挑战?
Cloudflare v3 挑战代表了机器人保护技术的最新演进。与传统 v1 和 v2 挑战不同,v3 挑战:
- **在 JavaScript 虚拟机中运行**:挑战在沙盒化的 JavaScript 环境中执行
- **使用高级检测**:更复杂的算法来检测自动化行为
- **生成动态代码**:挑战代码是动态创建的,更难进行逆向工程
- **提供现代保护**:来自 Cloudflare 的最新反机器人技术
### v3 基本用法```python
import cloudscraper
# v3 support is enabled by default
scraper = cloudscraper.create_scraper()
response = scraper.get("https://example.com")
print(response.text)
import cloudscraper
scraper = cloudscraper.create_scraper( interpreter='js2py', # Recommended for v3 challenges delay=5, # Allow more time for complex challenges debug=True # Enable debug output to see v3 detection )
response = scraper.get("https://example.com") print(response.text)
### v3 with Different JavaScript Interpreters
所有 JavaScript 解释器都适用于 v3 挑战:```python
# Test different interpreters for v3 challenges
interpreters = ['js2py', 'nodejs', 'native']
for interpreter in interpreters:
try:
scraper = cloudscraper.create_scraper(interpreter=interpreter)
response = scraper.get("https://example.com")
print(f"✅ {interpreter}: Success ({response.status_code})")
except Exception as e:
print(f"❌ {interpreter}: Failed - {str(e)}")
启用调试模式时,你会看到 v3 挑战检测的实际运行情况:```python scraper = cloudscraper.create_scraper(debug=True) response = scraper.get("https://example.com")
### v3 的性能注意事项
v3 的挑战更为复杂,可能需要更多时间:```python
# Recommended settings for v3 challenges
scraper = cloudscraper.create_scraper(
delay=5, # Longer delay for complex challenges
interpreter='js2py', # Most compatible interpreter
enable_stealth=True # Additional stealth for v3 detection
)
import cloudscraper
scraper = cloudscraper.create_scraper()
response = scraper.get("https://example.com") print(f"Status: {response.status_code}") print(f"Content length: {len(response.text)}")
### 示例 2:实现最大兼容性的高级配置```python
import cloudscraper
# Advanced configuration for challenging websites
scraper = cloudscraper.create_scraper(
# Challenge handling
interpreter='js2py', # Best compatibility for v3 challenges
delay=5, # Extra time for complex challenges
# Stealth mode
enable_stealth=True,
stealth_options={
'min_delay': 2.0,
'max_delay': 6.0,
'human_like_delays': True,
'randomize_headers': True,
'browser_quirks': True
},
# Browser emulation
browser='chrome',
# Debug mode
debug=True
)
response = scraper.get("https://example.com")
import cloudscraper
scraper = cloudscraper.create_scraper( captcha={ 'provider': '2captcha', 'api_key': 'your_2captcha_api_key' }, debug=True # See when Turnstile is detected and solved )
response = scraper.get("https://turnstile-protected-site.com") print(f"Successfully bypassed Turnstile: {response.status_code}")
### 示例 4:支持 v3 的代理轮换```python
import cloudscraper
proxies = [
'http://user:[email protected]:8080',
'http://user:[email protected]:8080',
'http://user:[email protected]:8080'
]
scraper = cloudscraper.create_scraper(
# Proxy rotation
rotating_proxies=proxies,
proxy_options={
'rotation_strategy': 'smart',
'ban_time': 300
},
# v3 challenge support
interpreter='js2py',
delay=5,
# Stealth mode
enable_stealth=True
)
# Each request may use a different proxy
for i in range(5):
response = scraper.get("https://example.com")
print(f"Request {i+1}: {response.status_code}")
import cloudscraper
def test_challenge_handling(): """Test different challenge types with comprehensive configuration"""
scraper = cloudscraper.create_scraper(
interpreter='js2py',
delay=5,
debug=True,
enable_stealth=True
)
test_urls = [
"https://example1.com", # Might have v1 challenges
"https://example2.com", # Might have v2 challenges
"https://example3.com", # Might have v3 challenges
"https://example4.com", # Might have Turnstile
]
for url in test_urls:
try:
response = scraper.get(url)
print(f"✅ {url}: Success ({response.status_code})")
except Exception as e:
print(f"❌ {url}: Failed - {str(e)}")
test_challenge_handling()
## 🧪 测试与验证
### 全面测试套件
cloudscraper 包含全面的测试脚本,用于验证所有功能是否正常工作:```bash
# Test all features
python test_all_features.py --debug
# Test specifically v3 challenges
python test_v3_challenges.py --debug
# Test with specific interpreter
python test_v3_challenges.py --interpreter nodejs
该库的核心功能已通过全面测试,成功率达 100%:
*需要外部配置(代理/API 密钥)
您可以使用调试模式手动测试该库,以实时观察挑战检测的实际运行情况:```python import cloudscraper
scraper = cloudscraper.create_scraper(debug=True) response = scraper.get("https://example.com")
### 故障排查
如果你遇到问题:
1. **启用调试模式** 以查看详细信息
2. **尝试不同的解释器**(js2py,nodejs,native)
3. **增加延迟** 以应对复杂挑战
4. **启用隐身模式** 以获得额外保护
5. **检查代理配置**(如果使用代理)```python
# Troubleshooting configuration
scraper = cloudscraper.create_scraper(
debug=True, # See what's happening
interpreter='js2py', # Most compatible
delay=10, # Extra time
enable_stealth=True # Additional protection
)
如果你不想尝试 Cloudflare v1(已弃用)的求解..
| 参数 | 值 | 默认值 |
|---|---|---|
| disableCloudflareV1 | (boolean) | False |
scraper = cloudscraper.create_scraper(disableCloudflareV1=True)
### 禁用 Cloudflare V2
#### 描述
如果你不想甚至尝试解决 Cloudflare v2..
#### 参数
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|disableCloudflareV2|(boolean)|False|
#### 示例```python
scraper = cloudscraper.create_scraper(disableCloudflareV2=True)
如果你甚至不想尝试 Cloudflare v3 JavaScript VM 求解..
| Parameter | Value | Default |
|---|---|---|
| disableCloudflareV3 | (boolean) | False |
scraper = cloudscraper.create_scraper(disableCloudflareV3=True)
### 禁用 Turnstile
#### 描述
如果你完全不想尝试解决 Cloudflare Turnstile 挑战..
#### 参数
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|disableTurnstile|(boolean)|False|
#### 示例```python
scraper = cloudscraper.create_scraper(disableTurnstile=True)
自动轮换代理列表以避免基于 IP 的封锁。
| 参数 | 值 | 默认值 |
|---|---|---|
| rotating_proxies | (列表或字典) | None |
| proxy_options | (字典) | {} |
proxy_options 参数| 参数 | 值 | 默认值 |
|---|---|---|
| rotation_strategy | (字符串)sequential、random 或 smart |
proxies = [ 'http://user:[email protected]:8080', 'http://user:[email protected]:8080', 'http://user:[email protected]:8080' ]
scraper = cloudscraper.create_scraper( rotating_proxies=proxies, proxy_options={ 'rotation_strategy': 'smart', 'ban_time': 300 } )
### 隐身模式
#### 描述
启用隐身技术,以更好地模仿人类行为并避免被检测。
#### 参数
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|enable_stealth|(boolean)|True|
|stealth_options|(dict)|{}|
#### `stealth_options` 参数
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|min_delay|(float) 请求之间的最小延迟|1.0|
|max_delay|(float) 请求之间的最大延迟|5.0|
|human_like_delays|(boolean) 在请求之间添加随机延迟|True|
|randomize_headers|(boolean) 随机化标头以避免指纹识别|True|
|browser_quirks|(boolean) 应用浏览器特有的怪癖|True|
#### 示例```python
scraper = cloudscraper.create_scraper(
enable_stealth=True,
stealth_options={
'min_delay': 2.0,
'max_delay': 6.0,
'human_like_delays': True,
'randomize_headers': True,
'browser_quirks': True
}
)
已添加 Brotli 解压缩支持,并且默认启用。
| 参数 | 值 | 默认值 |
|---|---|---|
| allow_brotli | (布尔值) | True |
scraper = cloudscraper.create_scraper(allow_brotli=False)
### 浏览器 / User-Agent 过滤
#### 描述
控制如何以及"随机"选择哪个 User-Agent。
#### 参数
可以作为参数传递给 `create_scraper()`、`get_tokens()`、`get_cookie_string()`。
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|browser|(字符串) `chrome` 或 `firefox`|None|
或
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|browser|(字典)||
##### `browser` *_dict_* 参数
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|browser|(字符串) `chrome` 或 `firefox`|None|
|mobile|(布尔值)|True|
|desktop|(布尔值)|True|
|platform|(字符串) `'linux', 'windows', 'darwin', 'android', 'ios'`|None|
|custom|(字符串)|None|
#### 示例```python
scraper = cloudscraper.create_scraper(browser='chrome')
或```python
scraper = cloudscraper.create_scraper( browser={ 'browser': 'chrome', 'platform': 'android', 'desktop': False } )
scraper = cloudscraper.create_scraper( browser={ 'browser': 'firefox', 'platform': 'windows', 'mobile': False } )
scraper = cloudscraper.create_scraper( browser={ 'custom': 'ScraperBot/1.0', } )
### Debug
#### 描述
打印请求的头部和内容信息以进行调试。
#### 参数
可以通过你的 `cloudscraper` 对象将其设置为属性,或作为参数传递给 `create_scraper()`、`get_tokens()`、`get_cookie_string()`。
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|debug|(boolean)|False|
#### 示例```python
scraper = cloudscraper.create_scraper(debug=True)
Cloudflare 的 IUAM 挑战要求浏览器在提交挑战答案前等待约 5 秒,如果您希望覆盖此延迟。
可以通过您的 cloudscraper 对象设置为属性,或作为参数传递给 create_scraper()、get_tokens()、get_cookie_string()。
| 参数 | 值 | 默认值 |
|---|---|---|
| delay | (float) | 从 IUAM 页面提取 |
scraper = cloudscraper.create_scraper(delay=10)
### Existing session
#### Description:
如果你已经有一个现有的 Requests 会话,你可以将其传递给 `create_scraper()` 函数以继续使用该会话。
#### Parameters
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|sess|(requests.session)|None|
#### 示例```python
session = requests.session()
scraper = cloudscraper.create_scraper(sess=session)
遗憾的是,并非所有 Requests 会话属性都易于迁移,因此如果在此遇到问题,
您应该替换最初的会话初始化调用
从:```python sess = requests.session()
收件人:```python
sess = cloudscraper.create_scraper()
cloudscraper 目前支持以下 JavaScript 引擎/解释器
可以通过你的 cloudscraper 对象作为属性设置,或作为参数传递给 create_scraper()、get_tokens()、get_cookie_string()。
| 参数 | 值 | 默认 |
|---|---|---|
| interpreter | (字符串) | js2py |
scraper = cloudscraper.create_scraper(interpreter='nodejs')
#### 注意
增强版默认使用 `js2py` 作为解释器,因为它能更好地兼容现代 Cloudflare 挑战。如果遇到问题,你可以尝试其他解释器。
------
### 第三方验证码求解器
#### 描述
`cloudscraper` 目前支持以下第三方验证码求解器,供你在需要时使用。
- **[2captcha](https://www.2captcha.com/)**
- **[anticaptcha](https://www.anti-captcha.com/)**
- **[CapSolver](https://capsolver.com/)**
- **[CapMonster Cloud](https://capmonster.cloud/)**
- **[deathbycaptcha](https://www.deathbycaptcha.com/)**
- **[9kw](https://www.9kw.eu/)**
- **__return_response__**
#### 注意
我正在努力添加更多第三方求解器。如果你希望添加当前尚未支持的服务,请在 github 上提交支持工单。
##### 必需参数
可以通过你的 `cloudscraper` 对象将其设置为属性,或作为参数传递给 `create_scraper()`、`get_tokens()`、`get_cookie_string()`。
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|captcha|(dict)|None|
#### Turnstile 支持
Cloudflare Turnstile 是一种新的 CAPTCHA 替代方案,用更友好的验证系统取代传统 CAPTCHA。cloudscraper 现在支持使用你已熟悉的同一批验证码提供商来解决 Turnstile 挑战。
##### 示例```python
# Using 2captcha to solve Turnstile challenges
scraper = cloudscraper.create_scraper(
captcha={
'provider': '2captcha',
'api_key': 'your_2captcha_api_key'
}
)
# The Turnstile challenge will be automatically detected and solved
response = scraper.get('https://example.com')
captcha 参数如果设置了代理,你可以通过将 no_proxy 设置为 True 来禁用向 2captcha 发送代理。
scraper = cloudscraper.create_scraper( captcha={ 'provider': '2captcha', 'api_key': 'your_2captcha_api_key' } )
#### anticaptcha
##### 必需的 `captcha` 参数
|参数|值|必需|默认|
|-------------|:-------------:|:-----:|:-----:|
|provider|(string) `anticaptcha`|是||
|api_key|(string)|是||
|no_proxy|(boolean)|否|False|
##### 注意
如果设置了代理,你可以通过将 `no_proxy` 设置为 `True` 来禁止将代理发送给 anticaptcha。
##### 示例```python
scraper = cloudscraper.create_scraper(
captcha={
'provider': 'anticaptcha',
'api_key': 'your_anticaptcha_api_key'
}
)
captcha 参数| 参数 | 值 | 必需 | 默认 |
|---|---|---|---|
| provider | (字符串) captchaai | 是 | |
| api_key | (字符串) | 是 |
scraper = cloudscraper.create_scraper( captcha={ 'provider': 'capsolver', 'api_key': 'your_captchaai_api_key' } )
#### CapMonster Cloud
##### 必填 `captcha` 参数
|参数|类型|必填|默认|
|-------------|:-------------:|:-----:|:-----:|
|provider|(string) `capmonster`| 是||
|clientKey|(string)| 是||
|no_proxy|(boolean)|否|False|
##### 注意
如果设置了代理,可以通过将 `no_proxy` 设置为 `True` 来禁用向 CapMonster 发送代理。
##### 示例```python
scraper = cloudscraper.create_scraper(
captcha={
'provider': 'capmonster',
'clientKey': 'your_capmonster_clientKey'
}
)
captcha 参数scraper = cloudscraper.create_scraper( captcha={ 'provider': 'deathbycaptcha', 'username': 'your_deathbycaptcha_username', 'password': 'your_deathbycaptcha_password', } )
#### 9kw
##### 必需的 `captcha` 参数
|参数|值|必填|默认|
|-------------|:-------------:|:-----:|:-----:|
|provider|(string) `9kw`|是||
|api_key|(string)|是||
|maxtimeout|(int)|否|180|
##### 示例```python
scraper = cloudscraper.create_scraper(
captcha={
'provider': '9kw',
'api_key': 'your_9kw_api_key',
'maxtimeout': 300
}
)
如果你想要获取请求的响应负载而不解决验证码,请使用此选项。
captcha 参数| 参数 | 值 | 必填 | 默认值 |
|---|---|---|---|
| provider | (string) return_response | 是 |
scraper = cloudscraper.create_scraper( captcha={'provider': 'return_response'} )
## 集成
将 `cloudscraper` 与其他应用和工具集成非常简单。Cloudflare 使用两个 Cookie 作为令牌:一个用于验证你是否通过了其质询页面,另一个用于跟踪你的会话。要绕过质询页面,只需在你发出的所有 HTTP 请求中同时包含这两个 Cookie(并附带适当的 user-agent)。
要仅检索 Cookie(以字典形式),请使用 `cloudscraper.get_tokens()`。要将其作为完整的 `Cookie` HTTP 头检索,请使用 `cloudscraper.get_cookie_string()`。
`get_tokens` 和 `get_cookie_string` 都接受 Requests 常用的关键字参数(例如 `get_tokens(url, proxies={"http": "socks5://localhost:9050"})`)。
请阅读 [Requests 关于请求参数的文档](http://docs.python-requests.org/en/master/api/#requests.Session.request) 以了解更多信息。
------
### User-Agent 处理
这两个集成函数返回一个 `(cookie, user_agent_string)` 元组。
**你必须在获取令牌和使用这些令牌发起请求时使用相同的 user-agent 字符串,否则 Cloudflare 会将你标记为机器人。**
这意味着你必须将返回的 `user_agent_string` 传递给任何你向其传递令牌的脚本、工具或服务(例如 curl 或专门的抓取工具),并且该工具在使用这些令牌发出 HTTP 请求时必须使用该传递的 user-agent。
------
### 集成示例
请记住,在检索或使用这些 Cookie 时,你必须始终使用相同的 user-agent。这些函数都返回一个 `(cookie_dict, user_agent_string)` 元组。
------
#### 通过代理检索 Cookie 字典
`get_tokens` 是一个便捷函数,用于返回包含 Cloudflare 会话 Cookie 的 Python 字典。为了演示,我们将配置此请求使用代理。(请注意,如果你通过代理请求 Cloudflare 清除令牌,则在将这些令牌传递给服务器时,必须始终使用相同的代理。Cloudflare 要求解决质询的 IP 与访问者 IP 保持一致。)
如果你不希望使用代理,只需不传递 `proxies` 关键字参数即可。这些便捷函数支持 Requests 的所有常规关键字参数,例如 `params`、`data` 和 `headers`。```python
import cloudscraper
# Using a single proxy
proxies = {"http": "http://localhost:8080", "https": "http://localhost:8080"}
tokens, user_agent = cloudscraper.get_tokens("http://somesite.com", proxies=proxies)
print(tokens)
# => {
'cf_clearance': 'c8f913c707b818b47aa328d81cab57c349b1eee5-1426733163-3600',
'__cfduid': 'dd8ec03dfdbcb8c2ea63e920f1335c1001426733158',
'cf_chl_2': 'some_value',
'cf_chl_prog': 'some_value'
}
# Using proxy rotation
rotating_proxies = [
'http://user:[email protected]:8080',
'http://user:[email protected]:8080',
'http://user:[email protected]:8080'
]
tokens, user_agent = cloudscraper.get_tokens(
"http://somesite.com",
rotating_proxies=rotating_proxies,
proxy_options={
'rotation_strategy': 'smart',
'ban_time': 300
},
enable_stealth=True,
stealth_options={
'min_delay': 2.0,
'max_delay': 6.0
}
)
get_cookie_string 是一个便捷函数,用于将令牌以字符串形式返回,以便作为 Cookie HTTP 头部的值使用。
这在手动构造 HTTP 请求,或与传递原始 cookie 头的外部应用程序或库协作时非常有用。```python import cloudscraper
cookie_value, user_agent = cloudscraper.get_cookie_string('http://somesite.com')
print('GET / HTTP/1.1\nCookie: {}\nUser-Agent: {}\n'.format(cookie_value, user_agent))
#### curl 示例
以下是将 cloudscraper 与 curl 集成的示例。如您所见,您只需将 cookies 和 user-agent 传递给 curl 即可。```python
import subprocess
import cloudscraper
# With get_tokens() cookie dict:
# tokens, user_agent = cloudscraper.get_tokens("http://somesite.com")
# cookie_arg = 'cf_clearance={}; __cfduid={}'.format(tokens['cf_clearance'], tokens['__cfduid'])
# With get_cookie_string() cookie header; recommended for curl and similar external applications:
cookie_arg, user_agent = cloudscraper.get_cookie_string('http://somesite.com')
# With a custom user-agent string you can optionally provide:
# ua = "Scraping Bot"
# cookie_arg, user_agent = cloudscraper.get_cookie_string("http://somesite.com", user_agent=ua)
result = subprocess.check_output(
[
'curl',
'--cookie',
cookie_arg,
'-A',
user_agent,
'http://somesite.com'
]
)
精简版。通过 curl 打印任何受 Cloudflare 保护的站点的页面内容。
警告:shell=True 在真实代码中与 subprocess 一起使用可能很危险。```python
url = "http://somesite.com"
cookie_arg, user_agent = cloudscraper.get_cookie_string(url)
cmd = "curl --cookie {cookie_arg} -A {user_agent} {url}"
print(
subprocess.check_output(
cmd.format(
cookie_arg=cookie_arg,
user_agent=user_agent,
url=url
),
shell=True
)
)
### Cryptography
#### 描述
控制客户端与服务器之间的通信
#### 参数
可以作为参数传递给 `create_scraper()`。
|参数|值|默认值|
|-------------|:-------------:|:-----:|
|cipherSuite|(string)|None|
|ecdhCurve|(string)|prime256v1|
|server_hostname|(string)|None|
#### 示例```python
# Some servers require the use of a more complex ecdh curve than the default "prime256v1"
# It may can solve handshake failure
scraper = cloudscraper.create_scraper(ecdhCurve='secp384r1')
I notice the input chunk is empty. There is no content provided to translate. Please provide the actual chunk content so I can translate it.```python
scraper = cloudscraper.create_scraper(server_hostname='www.somesite.com') scraper.get( 'https://backend.hosting.com/', headers={'Host': 'www.somesite.com'} )
# 增强功能
这个增强版 cloudscraper 提供了更好的能力来绕过现代 Cloudflare 保护机制:
1. **Cloudflare v2 挑战支持** - 更好地处理现代挑战
2. **代理轮换** - 支持多种策略的智能轮换
3. **隐身模式** - 模拟类人行为
4. **改进的 JavaScript 处理** - 更好的 JS 解释器(默认使用 js2py)
5. **增强的 Cookie 管理** - 支持更新的 Cloudflare cookie 类型
## 最近更新
- **代码库清理**:移除了冗余代码并整合为单一模块
- **测试套件更新**:所有测试现在都使用 cloudscraper 模块
- **文档**:改进了 README,提供了更清晰的示例和使用说明
## 使用所有增强功能的示例```python
import cloudscraper
# Create a scraper with all enhanced features
scraper = cloudscraper.create_scraper(
# Use js2py interpreter for better compatibility
interpreter='js2py',
# Enable proxy rotation
rotating_proxies=[
'http://user:[email protected]:8080',
'http://user:[email protected]:8080',
'http://user:[email protected]:8080'
],
proxy_options={
'rotation_strategy': 'smart',
'ban_time': 300
},
# Enable stealth mode
enable_stealth=True,
stealth_options={
'min_delay': 2.0,
'max_delay': 6.0,
'human_like_delays': True,
'randomize_headers': True,
'browser_quirks': True
},
# Set browser fingerprint
browser={
'browser': 'chrome',
'platform': 'windows',
'mobile': False
},
# Enable debugging if needed
debug=False
)
# Make a request to a Cloudflare-protected site
response = scraper.get('https://example.com')
print(response.text)
Cloudflare v3 JavaScript 虚拟机挑战支持
增强的 Turnstile 支持
JavaScript 解释器增强
挑战检测
配置选项
disableCloudflareV3 参数以选择性处理挑战全面的测试套件
文档
该库包含全面的测试脚本以验证功能:
快速测试以验证库是否正常工作:```python import cloudscraper
scraper = cloudscraper.create_scraper(browser='chrome')
response = scraper.get('https://example.com') print(f"Status code: {response.status_code}")
### 运行测试套件
该库包含几个测试脚本:```bash
# Run the comprehensive test suite
python test_cloudscraper_comprehensive.py https://example-cloudflare-site.com
# Test with a specific Cloudflare-protected site
python test_cloudflare_site.py https://example-cloudflare-site.com --browser firefox --stealth
如果遇到问题:
如有问题或疑问,请在 GitHub 仓库中提交 issue。```bash pip install --upgrade cloudscraper # Always use the latest version
| 功能 | 测试覆盖 | 通过率 |
|---|
| 基础请求 | ✅ 完整 | 100% |
| User-Agent 处理 | ✅ 完整 | 100% |
| Cloudflare v1 挑战 | ✅ 完整 | 100% |
| Cloudflare v2 挑战 | ✅ 完整 | 100% |
| Cloudflare v3 挑战 | ✅ 新增 | 100% |
| 隐身模式 | ✅ 完整 | 100% |
| JavaScript 解释器 | ✅ 全部支持 | 100% |
| 代理轮换 | ✅ 完整 | N/A* |
| Turnstile 支持 | ✅ 完整 | N/A* |
sequential| ban_time | (整数)失败后封禁代理的秒数 | 300 |
| 参数 | 值 | 必填 | 默认 |
|---|
| provider | (string) 2captcha | 是 | |
| api_key | (string) | 是 | |
| no_proxy | (boolean) | 否 | False |
| 参数 | 值 | 必填 | 默认值 |
|---|
| provider | (string) deathbycaptcha | 是 | |
| username | (string) | 是 | |
| password | (string) | 是 |