
CloudflareのアンチボットページをバイパスするPythonモジュール。
Zied Boughdir による拡張
すべての機能はコア機能で 100% の成功率 でテスト済み:
Requests を使用して実装された、Cloudflare のアンチボットページ (「I'm Under Attack Mode」または IUAM とも呼ばれる) をバイパスする Python モジュール。この拡張版には、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...
Any script using cloudscraper will sleep for ~5 seconds for the first visit to any site with Cloudflare anti-bots enabled, though no delay will occur after the first request.
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のアンチボットによって保護されているWebサイトに対して、このセッションオブジェクトから行われるリクエストは自動的に処理されます。Cloudflareを使用していないWebサイトは通常どおりに扱われます。追加で設定や呼び出しを行う必要はなく、すべてのWebサイトをあたかも何の保護も受けていないかのように扱うことができます。
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)
### 異なるJavaScriptインタープリターを使用したv3
すべての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 の解決を試みることすら望まない場合に使用します..
| パラメータ | 値 | デフォルト |
|---|---|---|
| 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 | (list または dict) | None |
| proxy_options | (dict) | {} |
proxy_options のパラメータ| パラメータ | 値 | デフォルト |
|---|---|---|
| rotation_strategy | (string) 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 | (boolean) | True |
scraper = cloudscraper.create_scraper(allow_brotli=False)
### ブラウザ / User-Agent フィルタリング
#### 説明
どの User-Agent を「ランダムに」選択するか、またその方法を制御します。
#### パラメータ
`create_scraper()`、`get_tokens()`、`get_cookie_string()` の引数として渡すことができます。
|パラメータ|値|デフォルト|
|-------------|:-------------:|:-----:|
|browser|(string) `chrome` または `firefox`|None|
または
|パラメータ|値|デフォルト|
|-------------|:-------------:|:-----:|
|browser|(dict)||
##### `browser` *_dict_* パラメータ
|パラメータ|値|デフォルト|
|-------------|:-------------:|:-----:|
|browser|(string) `chrome` または `firefox`|None|
|mobile|(boolean)|True|
|desktop|(boolean)|True|
|platform|(string) `'linux', 'windows', 'darwin', 'android', 'ios'`|None|
|custom|(string)|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', } )
### デバッグ
#### 説明
リクエストのヘッダーとコンテンツ情報をデバッグ用に出力します。
#### パラメータ
`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)
### 既存のセッション
#### 説明:
既存のRequestsセッションがすでにある場合、それを `create_scraper()` 関数に渡して、そのセッションを引き続き使用できます。
#### パラメータ
|パラメータ|値|デフォルト|
|-------------|:-------------:|:-----:|
|sess|(requests.session)|None|
#### 例```python
session = requests.session()
scraper = cloudscraper.create_scraper(sess=session)
残念ながら、Requests のセッション属性のすべてが簡単に引き継げるわけではありません。そのため、これで問題が発生した場合は、
最初のセッション初期化呼び出しを置き換える必要があります。
変更前:```python sess = requests.session()
To:```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チャレンジとの互換性が向上するためです。問題が発生した場合は、他のインタープリタを試すことができます。
------
### サードパーティCAPTCHAソルバー
#### 説明
`cloudscraper` は、必要に応じて以下のサードパーティCAPTCHAソルバーをサポートしています。
- **[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は、あなたがすでに使い慣れているのと同じCAPTCHAプロバイダーを使用して、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 | (string) captchaai | はい | |
| api_key | (string) | はい |
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を解決せずにリクエストのレスポンスペイロードを取得したい場合は、これを使用します。
captcha パラメータ| パラメータ | 値 | 必須 | デフォルト |
|---|---|---|---|
| provider | (string) return_response | yes |
scraper = cloudscraper.create_scraper( captcha={'provider': 'return_response'} )
## Integration
`cloudscraper` を他のアプリケーションやツールと統合するのは簡単です。Cloudflare はトークンとして2つの Cookie を使用します。1つはチャレンジページを通過したことを確認するため、もう1つはセッションを追跡するためです。チャレンジページを回避するには、行うすべての 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 の取り扱い
2つの統合関数は、`(cookie, user_agent_string)` のタプルを返します。
**トークンを取得するときと、そのトークンを使ってリクエストを行うときには、同じ user-agent 文字列を使用する必要があります。そうしないと、Cloudflare にボットとして判定されます。**
つまり、トークンを渡すスクリプト、ツール、サービス(例: curl や専用のスクレイピングツール)に対して、返された `user_agent_string` を渡し、そのツールが HTTP リクエストを行う際にその渡された user-agent を使用する必要があります。
------
### 統合例
これらの Cookie を取得または使用するときは、常に同じ user-agent を使用する必要があることに注意してください。これらの関数はすべて `(cookie_dict, user_agent_string)` のタプルを返します。
------
#### プロキシ経由で Cookie 辞書を取得する
`get_tokens` は、Cloudflare のセッション Cookie を含む Python の dict を返す便利な関数です。デモンストレーションとして、このリクエストがプロキシを使用するように設定します。(Cloudflare のクリアランストークンをプロキシ経由でリクエストする場合は、それらのトークンがサーバーに渡されるときも常に同じプロキシを使用する必要があることに注意してください。Cloudflare は、チャレンジ解決 IP と訪問者 IP が同じであることを要求します。)
プロキシを使用したくない場合は、`proxies` キーワード引数を渡さないだけです。これらの便利な関数は、`params`、`data`、`headers` など、Requests の通常のキーワード引数をすべてサポートしています。```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 で保護された任意のサイトのページ内容を表示します。
警告: 実際のコードで subprocess と一緒に shell=True を使用すると危険な場合があります。```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
)
)
### 暗号
#### 説明
クライアントとサーバー間の通信を制御します。
#### パラメータ
`create_scraper()` の引数として渡すことができます。
|パラメータ|値|デフォルト|
|-------------|:-------------:|:-----:|
|cipherSuite|(文字列)|None|
|ecdhCurve|(文字列)|prime256v1|
|server_hostname|(文字列)|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')
(入力コンテンツが提供されていません。翻訳対象のMarkdownテキストを貼り付けてください。)```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 VM チャレンジのサポート
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% |
| ユーザーエージェント処理 | ✅ 完全 | 100% |
| Cloudflare v1 チャレンジ | ✅ 完全 | 100% |
| Cloudflare v2 チャレンジ | ✅ 完全 | 100% |
| Cloudflare v3 チャレンジ | ✅ 新規 | 100% |
| ステルスモード | ✅ 完全 | 100% |
| JavaScript インタープリター | ✅ すべて対応 | 100% |
| プロキシローテーション | ✅ 完全 | N/A* |
| Turnstile サポート | ✅ 完全 | N/A* |
sequential |
| ban_time | (int) 失敗後にプロキシを禁止する秒数 | 300 |
| パラメータ | 値 | 必須 | デフォルト |
|---|
| provider | (string) 2captcha | はい | |
| api_key | (string) | はい | |
| no_proxy | (boolean) | いいえ | False |
| パラメータ | 値 | 必須 | デフォルト |
|---|
| provider | (string) deathbycaptcha | はい | |
| username | (string) | はい | |
| password | (string) | はい |