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

如何在Python Selenium中集成2Captcha API绕过reCAPTCHA

解决Reddit注册流程中reCAPTCHA的2Captcha集成问题

你的代码已经调用了2Captcha API获取reCAPTCHA验证结果,但缺少将验证token回填到页面并完成提交的关键步骤,这就是验证框没被绕过的核心原因。以下是完整的修正方案:

核心步骤补充

  1. 等待reCAPTCHA控件加载完成:调用2Captcha前,确保页面上的reCAPTCHA已完全渲染,避免提前请求导致无效。
  2. 回填验证token到页面:2Captcha返回的code字段是验证所需token,需注入到页面的隐藏输入框g-recaptcha-response中。
  3. 触发表单提交:回填完成后,模拟点击注册按钮完成提交。

修正后的代码片段

import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.proxy import *
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import time
import openpyxl
import requests
from twocaptcha import TwoCaptcha

# 初始化2Captcha solver
solver = TwoCaptcha('YOUR_API_KEY')

# Load the Excel file
...
# Loop through the rows of the DataFrame
...
   # Get the latest IP address from the proxy service
   ...
   # Update the capabilities object to use the new proxy
   ...
   # 创建webdriver实例(推荐用undetected-chromedriver绕过反爬)
   driver = webdriver.Chrome(desired_capabilities=capabilities)
   driver.get('https://www.reddit.com/account/register/')

   # 填写用户名和密码(补充你原有的填写逻辑)
   driver.find_element(By.ID, 'regUsername').send_keys(username)
   driver.find_element(By.ID, 'regPassword').send_keys(password)

   # 等待reCAPTCHA加载完成
   WebDriverWait(driver, 10).until(
       EC.presence_of_element_located((By.CSS_SELECTOR, 'div.g-recaptcha'))
   )

   # 调用2Captcha获取验证token
   try:
       result = solver.recaptcha(
           sitekey='6LeTnxkTAAAAAN9QEuDZRpn90WwKk_R1TRW_g-JC',
           url='https://www.reddit.com/account/register/'
       )
       captcha_token = result['code']
   except Exception as e:
       print(f"2Captcha请求失败: {e}")
       driver.quit()
       continue

   # 将token注入页面隐藏字段
   driver.execute_script(f'document.getElementById("g-recaptcha-response").innerHTML = "{captcha_token}";')

   # 模拟点击注册按钮(根据实际页面调整选择器)
   register_btn = driver.find_element(By.XPATH, '//button[contains(text(), "Sign Up")]')
   register_btn.click()

   # 等待页面跳转或处理后续逻辑
   sleep(5)
   driver.quit()

关键注意事项

  • 核对sitekey有效性:Reddit可能更新reCAPTCHA的sitekey,建议在浏览器开发者工具中重新确认当前注册页的sitekey是否与代码中一致。
  • 使用反检测浏览器:普通ChromeDriver易被反爬机制识别,推荐改用undetected-chromedriver,安装命令:pip install undetected-chromedriver,替换原有webdriver初始化逻辑。
  • 控制操作节奏:用WebDriverWait替代固定sleep,模拟真实用户操作速度,避免触发频率限制。
  • 确保代理可用性:Selenium使用的代理需稳定且未被Reddit封禁,2Captcha本身无需代理,但浏览器会话代理必须能正常访问Reddit。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:05:17