
Cloudflare의 안티봇 페이지를 우회하는 Python 모듈
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는 계속 호환되므로 코드에서 import 문만 변경하면 됩니다. 모든 함수 호출과 매개변수는 동일하게 작동합니다.
### 코드베이스 구조
코드베이스는 유지보수성을 높이고 혼란을 줄이기 위해 간소화되었습니다:
- **단일 모듈**: 모든 코드는 이제 `cloudscraper` 모듈에 있습니다.
- **중복 제거**: 중복 디렉터리가 제거되었습니다.
- **테스트 업데이트**: 모든 테스트 파일이 `cloudscraper` 모듈을 사용하도록 업데이트되었습니다.
이로써 코드베이스가 더 깔끔해지고 유지보수가 쉬워지며, 기존 API를 사용하는 기존 코드와의 하위 호환성도 보장됩니다.
## cloudscraper의 주요 기능
| 기능 | 설명 | 상태 |
|---------|-------------|--------|
| **🆕 실행 파일 호환성** | PyInstaller, cx_Freeze, auto-py-to-exe 변환에 대한 완전한 수정 | ✅ **수정 완료** |
| **🆕 v3 JavaScript VM 챌린지** | Cloudflare의 최신 JavaScript VM 기반 챌린지 지원 | ✅ **신규** |
| **🆕 Turnstile 지원** | Cloudflare의 새로운 Turnstile CAPTCHA 대체 지원 | ✅ **신규** |
| **최신 챌린지 지원** | v1, v2, v3 및 Turnstile Cloudflare 챌린지에 대한 향상된 지원 | ✅ 완료 |
| **프록시 로테이션** | 여러 전략을 사용하는 내장형 스마트 프록시 로테이션 | ✅ 향상됨 |
| **스텔스 모드** | 탐지를 피하기 위한 인간과 유사한 행동 시뮬레이션 | ✅ 향상됨 |
| **브라우저 에뮬레이션** | Chrome 및 Firefox를 위한 고급 브라우저 핑거프린팅 | ✅ 안정적 |
| **JavaScript 처리** | 챌린지 해결을 위한 더 나은 JS 인터프리터(기본값 js2py) | ✅ 향상됨 |
| **CAPTCHA 솔버** | 여러 CAPTCHA 해결 서비스 지원 | ✅ 안정적 |
# 의존성
- **Python 3.8+** (Python 3.6 및 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`은 Python 의존성을 자동으로 설치합니다. 직접 설치해야 하는 것은 사용자가 선택한 Javascript 인터프리터 및/또는 엔진뿐이며, 기본값으로 요구 사항에 포함된 js2py는 제외됩니다.
# Javascript 인터프리터 및 엔진
우리는 다음 Javascript 인터프리터/엔진을 지원합니다.
- **[ChakraCore](https://github.com/microsoft/ChakraCore):** 라이브러리 바이너리는 [여기](https://www.github.com/VeNoMouS/cloudscraper/tree/ChakraCore/)에서도 확인할 수 있습니다.
- **[js2py](https://github.com/PiotrDabkowski/Js2Py):** >=0.74 **(향상된 버전의 기본값)**
- **native**: 자체 제작 네이티브 python 솔버
- **[Node.js](https://nodejs.org/)**
- **[V8](https://github.com/sony/v8eval/):** Sony의 [v8eval](https://v8.dev)() python 모듈을 사용합니다.
# 사용법
cloudscraper를 사용하는 가장 간단한 방법은 `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 애플리케이션을 실행 파일로 변환할 때 발생하던 user agent 문제가 완전히 해결되었습니다!
Python 앱을 실행 파일로 변환할 때(PyInstaller, cx_Freeze, auto-py-to-exe 등 사용) browsers.json 파일이 제대로 포함되지 않아 user agent 또는 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
Your 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)
### Disable 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()
받는 사람:```python
sess = cloudscraper.create_scraper()
cloudscraper는 현재 다음 JavaScript 엔진/인터프리터를 지원합니다.
cloudscraper 객체의 속성으로 설정하거나 create_scraper(), get_tokens(), get_cookie_string()에 인자로 전달할 수 있습니다.
| 매개변수 | 값 | 기본값 |
|---|---|---|
| interpreter | (string) | 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
##### Required `captcha` Parameters
|Parameter|Value|Required|Default|
|-------------|:-------------:|:-----:|:-----:|
|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를 풀지 않고 requests 응답 페이로드를 원하는 경우 사용합니다.
captcha 매개변수| 매개변수 | 값 | 필수 | 기본값 |
|---|---|---|---|
| provider | (string) return_response | 예 |
scraper = cloudscraper.create_scraper( captcha={'provider': 'return_response'} )
## 통합
`cloudscraper`를 다른 애플리케이션 및 도구와 통합하는 것은 쉽습니다. Cloudflare는 두 개의 쿠키를 토큰으로 사용합니다. 하나는 챌린지 페이지를 통과했는지 확인하는 용도이고, 다른 하나는 세션을 추적하는 용도입니다. 챌린지 페이지를 우회하려면 모든 HTTP 요청에 이 두 쿠키를 (적절한 user-agent와 함께) 포함하기만 하면 됩니다.
쿠키만 (딕셔너리로) 가져오려면 `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를 사용해야 합니다.
------
### 통합 예제
쿠키를 가져오거나 사용할 때 항상 동일한 user-agent를 사용해야 한다는 점을 기억하세요. 이 함수들은 모두 `(cookie_dict, user_agent_string)` 튜플을 반환합니다.
------
#### 프록시를 통한 쿠키 딕셔너리 가져오기
`get_tokens`는 Cloudflare의 세션 쿠키를 포함하는 Python 딕셔너리를 반환하는 편의 함수입니다. 데모를 위해 이 요청이 프록시를 사용하도록 구성하겠습니다. (참고: 프록시를 통해 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 요청을 수동으로 작성하거나, 원시 쿠키 헤더를 전달하는 외부 애플리케이션이나 라이브러리와 함께 작업할 때 유용합니다.```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과 통합하는 예제입니다. 보시다시피 쿠키와 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|(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')
Please provide the Markdown content to translate.```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. **향상된 쿠키 관리** - 최신 Cloudflare 쿠키 유형 지원
## 최근 업데이트
- **코드베이스 정리**: 중복 코드를 제거하고 단일 모듈로 통합
- **테스트 스위트 업데이트**: 모든 테스트가 이제 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 저장소에 이슈를 열어 주세요.```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) | 예 |