什么是 Cloudflare 5 秒盾
Cloudflare 的 “5 秒盾”(也称为 Browser Check 或 JS Challenge)是一种反爬虫机制。当用户访问受保护的页面时,会被拦截到一个中间页面,要求等待约 5 秒并通过 JavaScript 验证,验证通过后才能访问实际内容。
绕过方法
方法一:使用 curl_cffi
curl_cffi 是一个 Python 库,可以模拟真实浏览器的 TLS 指纹和 HTTP/2 行为,从而绕过 Cloudflare 的 JS 挑战。
1from curl_cffi import requests
2
3# 模拟 Chrome 浏览器指纹
4response = requests.get(
5 "https://example.com",
6 impersonate="chrome110"
7)
8
9print(response.status_code)
10print(response.text)
安装:
1pip install curl_cffi
方法二:使用 undetected-chromedriver
undetected-chromedriver 是 Selenium 的增强版,可以绕过 Cloudflare 的自动化检测。
1import undetected_chromedriver as uc
2
3driver = uc.Chrome()
4driver.get("https://example.com")
5
6# 等待页面加载
7import time
8time.sleep(6)
9
10print(driver.page_source)
11driver.quit()
安装:
1pip install undetected-chromedriver
方法三:使用 DrissionPage
DrissionPage 是一个基于 Python 的网页自动化工具,结合了 requests 和 Selenium 的优点。
1from DrissionPage import SessionPage
2
3page = SessionPage()
4page.get("https://example.com")
5
6# 等待 Cloudflare 验证通过
7page.wait(6)
8
9print(page.html)
安装:
1pip install DrissionPage
方法四:使用 Cloudflare 的 clearance cookie
如果只需要偶尔访问,可以手动获取 clearance cookie 后使用:
1import requests
2
3cookies = {
4 "cf_clearance": "从浏览器开发者工具中复制的值"
5}
6
7response = requests.get(
8 "https://example.com",
9 cookies=cookies
10)
注意事项
- 合法性:仅用于合法用途,如测试自己的网站
- Cookie 有效期:cf_clearance cookie 通常有效期为 30 分钟到 2 小时
- IP 信誉:即使绕过 JS 挑战,低信誉 IP 仍可能被拦截
- 更新频率:Cloudflare 会定期更新检测机制,需要保持工具更新
总结
| 方法 | 难度 | 稳定性 | 速度 |
|---|---|---|---|
| curl_cffi | 低 | 高 | 快 |
| undetected-chromedriver | 中 | 高 | 慢 |
| DrissionPage | 低 | 中 | 中 |
| 手动 Cookie | 低 | 低 | 快 |
推荐使用 curl_cffi,简单高效。