
Ethan Collins
Pattern Recognition Specialist

reCAPTCHA is the most common verification challenge AI agents encounter when browsing the web. LangChain agents performing data collection, form submission, or multi-step workflows hit reCAPTCHA v2 checkboxes and invisible challenges on login pages, search results, and protected content. This tutorial demonstrates how to solve reCAPTCHA v2 specifically within LangChain using CapSolver's capsolver-agent package, with complete code examples for both Token mode and Browser mode.
capsolver-agent package provides native BaseTool implementations for LangChain's ReAct agentsreCAPTCHA v2 is deployed on millions of websites to distinguish human users from automated traffic. When a LangChain agent navigates to a protected page — whether for lead enrichment, data extraction, or workflow automation — Google's risk analysis engine evaluates the session. Automated browsers, headless environments, and rapid navigation patterns trigger the reCAPTCHA challenge, halting the agent's execution.
The challenge manifests in two forms: the visible checkbox ("I'm not a robot") that requires interaction, and the invisible variant that triggers silently based on risk score. Both forms require a valid token submission to proceed. Without a solving mechanism, the LangChain agent cannot continue its task, and the entire chain fails.
Google's reCAPTCHA documentation confirms that the system uses advanced risk analysis including browser environment checks, interaction patterns, and historical behavior. This makes reCAPTCHA particularly challenging for automated agents that lack human-like browsing patterns.
CapSolver's AI-powered solving service handles reCAPTCHA v2 by generating valid tokens through its cloud infrastructure, bypassing the need for pixel-perfect interaction or image recognition within the agent's context window.
Install the required packages:
# Core engine (required dependency)
pip install git+https://github.com/capsolver-ai/capsolver-core.git
# Agent tools with LangChain support
pip install "capsolver-agent[langchain] @ git+https://github.com/capsolver-ai/capsolver-agent.git"
# LangChain runtime
pip install langchain-openai langgraph
Set environment variables:
export CAPSOLVER_API_KEY="your-capsolver-api-key"
export OPENAI_API_KEY="your-openai-api-key"
You also need the reCAPTCHA site key from your target page. Use the CapSolver browser extension to identify it, or inspect the page source for data-sitekey attributes. The reCAPTCHA identification guide explains how to distinguish between v2 checkbox, v2 invisible, and v3 variants.
Locate the reCAPTCHA site key on your target page. Open browser developer tools and search the page source:
<!-- Visible reCAPTCHA v2 (checkbox) -->
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<!-- Invisible reCAPTCHA v2 -->
<div class="g-recaptcha" data-sitekey="6LeIxAcT..." data-size="invisible"></div>
Record three values: the data-sitekey, the full page URL, and whether it's visible or invisible (check for data-size="invisible").
For programmatic detection using the CapSolver SDK:
from capsolver_core import create_capsolver
from playwright.async_api import async_playwright
async def detect_recaptcha(url: str):
cap = create_capsolver(api_key="YOUR_API_KEY")
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(url)
# Auto-detect all CAPTCHAs on the page
infos = await cap.get_captcha_info(page)
for info in infos:
print(f"Type: {info.type}, Key: {info.website_key}")
await browser.close()
await cap.aclose()
The site key is the essential parameter for reCAPTCHA solving. Without it, the solving service cannot generate a valid token for the specific site. Different pages on the same domain may use different site keys, so always verify per-page.
6LeIxAcT...) that always pass. Real sites use unique keys that require actual solving.page_action. Check the script source — v3 loads via ?render=SITE_KEY rather than a div element.Use the capsolver-agent LangChain tools to solve reCAPTCHA v2 within your agent's workflow:
import asyncio
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from capsolver_agent.langchain import get_langchain_tools
async def solve_recaptcha_with_agent():
# Get CapSolver LangChain tools
tools = get_langchain_tools(api_key="YOUR_CAPSOLVER_API_KEY")
# Create ReAct agent
llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = create_react_agent(llm, tools=tools)
# Ask the agent to solve reCAPTCHA
result = await agent.ainvoke({
"messages": [("user",
"Solve the reCAPTCHA v2 on https://example.com/login. "
"The site key is 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI. "
"Return the token I can use to submit the form."
)]
})
print(result["messages"][-1].content)
asyncio.run(solve_recaptcha_with_agent())
For direct execution without the agent loop (when you want programmatic control):
from capsolver_agent.schema import create_executor
async def solve_recaptcha_direct():
executor = create_executor(api_key="YOUR_CAPSOLVER_API_KEY")
result = await executor.execute("solve_captcha", {
"captcha_type": "reCaptchaV2",
"website_url": "https://example.com/login",
"website_key": "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
})
if result["success"]:
token = result["solution"]["token"]
print(f"reCAPTCHA solved! Token: {token[:60]}...")
# Submit this token as 'g-recaptcha-response' in your form POST
return token
else:
print(f"Failed: {result['error']}")
return None
The token returned should be submitted as the g-recaptcha-response field in the form POST request. The reCAPTCHA v2 solving documentation provides additional details on token submission patterns.
Token mode is the fastest approach for reCAPTCHA v2 — average solve time is 5-12 seconds with no browser overhead. For LangChain agents that already know the target site's parameters, this provides immediate CAPTCHA clearing without launching a browser instance.
Invisible reCAPTCHA v2 works identically from the API perspective — the same reCaptchaV2 task type handles both variants:
# Invisible reCAPTCHA v2 — same API call
result = await executor.execute("solve_captcha", {
"captcha_type": "reCaptchaV2",
"website_url": "https://example.com/checkout",
"website_key": "6Ld_SITE_KEY_HERE"
# No additional flag needed — CapSolver handles invisible automatically
})
The difference is in how you inject the token. Invisible reCAPTCHA typically binds to a button click or form submission event. After obtaining the token, trigger the callback:
# In a Playwright/browser context after solving:
await page.evaluate(f"""() => {{
document.getElementById('g-recaptcha-response').innerHTML = '{token}';
// Trigger the bound callback
if (typeof ___grecaptcha_cfg !== 'undefined') {{
const clients = ___grecaptcha_cfg.clients;
for (const key in clients) {{
const client = clients[key];
// Find and call the callback
if (client && client.L && client.L.L && client.L.L.callback) {{
client.L.L.callback('{token}');
}}
}}
}}
}}""")
The reCAPTCHA callback identification guide explains how to locate the correct callback function for any site.
When your LangChain agent drives a browser and encounters reCAPTCHA dynamically, use solve_on_page() for automatic detection and fill-back:
import asyncio
from capsolver_core import create_capsolver
from playwright.async_api import async_playwright
async def auto_solve_recaptcha(target_url: str):
"""Automatically detect and solve reCAPTCHA on any page."""
cap = create_capsolver(api_key="YOUR_CAPSOLVER_API_KEY")
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto(target_url)
await page.wait_for_load_state("networkidle")
# One call handles everything: detect → solve → fill back
results = await cap.solve_on_page(page)
for r in results:
if r.solution:
print(f"Solved {r.info.type}: token={r.solution.token[:50]}...")
print(f"Token filled into page: {r.filled}")
else:
print(f"Failed to solve {r.info.type}: {r.error}")
# After solving, the page is ready — submit the form
submit_button = page.locator('button[type="submit"]')
if await submit_button.count() > 0:
await submit_button.click()
await page.wait_for_navigation()
print(f"Form submitted. Current URL: {page.url}")
await browser.close()
await cap.aclose()
asyncio.run(auto_solve_recaptcha("https://example.com/login"))
Browser mode is particularly powerful because it reads the reCAPTCHA parameters directly from the live DOM — no manual site key extraction needed. The SDK identifies the CAPTCHA type, reads the data-sitekey, solves it, and writes the token back into the g-recaptcha-response textarea automatically.
Claim Your Bonus Code: Use code WEBS at CapSolver Dashboard to get an extra 5% bonus on every recharge. Ideal for LangChain developers building agents that handle reCAPTCHA challenges.
Combine reCAPTCHA solving with other tools for a complete production workflow:
import asyncio
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from capsolver_agent.langchain import get_langchain_tools
async def production_agent():
capsolver_tools = get_langchain_tools(api_key="YOUR_CAPSOLVER_API_KEY")
llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = create_react_agent(llm, tools=capsolver_tools)
# Multi-step task that requires reCAPTCHA solving
result = await agent.ainvoke({
"messages": [("user",
"I need to access a protected resource. "
"First, solve the reCAPTCHA v2 at https://example.com/gate "
"(site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI), "
"then tell me the token so I can proceed with my request."
)]
})
return result["messages"][-1].content
asyncio.run(production_agent())
For agents that need to handle multiple reCAPTCHA versions across different sites, the same tools handle both v2 and v3 — just change the captcha_type parameter from reCaptchaV2 to reCaptchaV3.
The CapSolver products page lists all supported CAPTCHA types and their pricing, helping you estimate costs for your LangChain agent deployment.
Solving reCAPTCHA in LangChain requires the capsolver-agent package with the LangChain extra, which provides native BaseTool implementations. Token mode handles known site keys in 5-12 seconds without a browser, while Browser mode auto-detects and fills reCAPTCHA tokens on any page. CapSolver powers the AI solving infrastructure, supporting both reCAPTCHA v2 checkbox and invisible variants through a unified interface.
Start by identifying the site key on your target page, then integrate get_langchain_tools() into your ReAct agent. The agent's reasoning loop naturally decides when to invoke reCAPTCHA solving, making verification handling a transparent part of your automation workflow.
CapSolver achieves a 95-99% success rate on reCAPTCHA v2 challenges. The AI-powered solving service handles both checkbox and invisible variants. Failed attempts are not charged, and the structured error response allows your agent to retry automatically.
Average solve time for reCAPTCHA v2 is 5-12 seconds. This includes network round-trip time to CapSolver's service and the AI recognition process. For time-sensitive workflows, the SDK supports configurable timeouts and polling intervals.
Yes. Pass enterprise: true in the parameters when calling solve_captcha. reCAPTCHA Enterprise uses the same v2/v3 task types but may require additional parameters like the s token. The CapSolver service handles Enterprise variants transparently.
No. Token mode works without any browser — you provide the site key and URL, and receive a token back. Browser mode (requiring Playwright) is optional and used when you want automatic detection and fill-back on live pages. Most LangChain integrations use Token mode for simplicity and speed.
reCAPTCHA tokens expire after approximately 120 seconds. Request the token as close to form submission as possible. If your workflow has delays between solving and submission, implement a "solve just before submit" pattern rather than solving early in the pipeline.
Complete guide to integrating CapSolver CAPTCHA solving into LangChain agents using capsolver-agent tools for reCAPTCHA, Cloudflare Turnstile, and more.

Learn how enterprise AI agent teams can implement scalable, reliable CAPTCHA solving infrastructure to keep automation workflows running without interruption.
