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

如何通过Python从Cookies中获取g-recaptcha_response值?

解决方案:获取g-recaptcha_response值

首先明确:g-recaptcha-response 并不会存储在Cookie中,它是Google reCAPTCHA验证通过后生成的临时令牌,由前端JavaScript生成,通常在表单提交时作为请求参数传递。由于reCAPTCHA需要人机交互验证,纯requests库(无浏览器环境)无法完成验证流程,需要使用浏览器自动化工具模拟用户操作。

方法:使用Selenium模拟浏览器获取令牌

以下是完整实现步骤:

  1. 安装依赖
pip install selenium webdriver-manager
  1. 代码实现
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time
import requests

# 初始化浏览器
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://example.com")  # 替换为目标网站的实际URL

# 等待reCAPTCHA加载完成(根据实际页面加载速度调整等待时间)
time.sleep(5)

# 触发隐形reCAPTCHA验证(对应页面中的隐形reCAPTCHA元素)
try:
    recaptcha_element = driver.find_element(By.ID, "recaptcha")
    driver.execute_script("arguments[0].click();", recaptcha_element)
except Exception as e:
    print(f"触发reCAPTCHA失败: {e}")

# 等待手动完成人机验证(这里暂停10秒,足够完成验证操作,可按需调整)
time.sleep(10)

# 提取g-recaptcha-response令牌
try:
    recaptcha_response = driver.execute_script("return document.getElementById('g-recaptcha-response').value;")
    print(f"g-recaptcha-response: {recaptcha_response}")
except Exception as e:
    print(f"获取令牌失败: {e}")

# 使用令牌发送后续请求
url = 'https://example.com/php/getReCaptchaResponse.php'
payload = {
    'g-recaptcha-response': recaptcha_response
}
response = requests.post(url, data=payload)

# 关闭浏览器
driver.quit()

关键说明

  • 若目标网站是普通reCAPTCHA(带复选框),需将触发验证的代码改为模拟点击复选框元素。
  • 人机验证环节需手动完成,使用第三方打码服务可能违反网站规则,需谨慎操作。
  • g-recaptcha-response 令牌有有效期,需在验证完成后立即用于请求。

内容的提问来源于stack exchange,提问作者Dkdkdkk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:18:31