You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium/undetected_chromedriver过Cloudflare并传入Requests会话?

问题:传递Cloudflare验证后的Cookie到Requests会话仍被拦截的解决办法

加密货币交易所hotbit.io禁用了我此前使用的部分重要接口,目前只能使用受Cloudflare保护的接口。我尝试用undetected_chromedriver完成Cloudflare验证,再将浏览器生成的Cookie传递至Requests会话,但执行后Requests仍停留在Cloudflare验证页面。我的代码如下:

import time

import requests
import undetected_chromedriver as uc

# 创建浏览器并完成Cloudflare验证
driver = uc.Chrome()
url = "https://www.hotbit.io/"
driver.get(url)
time.sleep(5)

# 存储浏览器生成的Cookie
request_cookies_browser = driver.get_cookies()
print(request_cookies_browser)

s = requests.Session()

# 将浏览器Cookie传递到会话
c = [s.cookies.set(c['name'], c['value']) for c in request_cookies_browser]

print(s.cookies)

resp = s.get(url)
print(resp.text)

解决方法

1. 同步User-Agent

Cloudflare会校验请求的User-Agent,Requests默认的UA和浏览器不一致会被拦截。需要把浏览器的UA同步到Requests会话:

# 在获取Cookie后添加
user_agent = driver.execute_script("return navigator.userAgent;")
s.headers.update({"User-Agent": user_agent})

2. 完整导入Cookie属性

直接用set方法可能丢失Cookie的domain、path等关键属性,改用完整导入方式:

# 替换原有的Cookie传递代码
for cookie in request_cookies_browser:
    s.cookies.set(
        cookie['name'], 
        cookie['value'], 
        domain=cookie['domain'], 
        path=cookie['path']
    )

同时确认Cookie中包含cf_clearance——这是Cloudflare验证通过的核心标识,若没有则说明浏览器未完成验证(可延长等待时间或手动完成验证)。

3. 同步请求头指纹

Cloudflare还会校验Accept、Accept-Language、Referer等请求头,直接复制浏览器的请求头到会话:

s.headers.update({
    "User-Agent": user_agent,
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.5",
    "Referer": url
})

4. 确保域名一致性

浏览器和Requests请求的域名必须完全一致(比如统一用https://www.hotbit.io,不要混用不带www的域名),否则Cookie无法生效。


修改后的完整代码示例

import time
import requests
import undetected_chromedriver as uc

# 创建浏览器并完成Cloudflare验证
driver = uc.Chrome()
url = "https://www.hotbit.io/"
driver.get(url)
# 延长等待时间确保验证完成,也可改为等待页面特定元素加载
time.sleep(10)

# 获取浏览器UA和Cookie
user_agent = driver.execute_script("return navigator.userAgent;")
request_cookies_browser = driver.get_cookies()

# 初始化Requests会话并配置
s = requests.Session()
s.headers.update({
    "User-Agent": user_agent,
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.5",
    "Referer": url
})

# 完整导入Cookie
for cookie in request_cookies_browser:
    s.cookies.set(cookie['name'], cookie['value'], domain=cookie['domain'], path=cookie['path'])

# 测试请求
resp = s.get(url)
print(resp.text)
driver.quit()

内容的提问来源于stack exchange,提问作者1220.moritz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 05:15:32