Was this helpful?
How to solve and bypass text captcha (letter captcha): Code examples
Tech builder focused on infrastructure, automation, backend systems, and scalable SaaS development
Reasons for Seeking Automation Solutions
CAPTCHAs create barriers for users with disabilities, requiring the development of more inclusive solutions.
Automated bypassing requires advanced machine learning models or API services, which adds complexity to automation. Below are complete instructions for the most common programming languages.
Types of Text CAPTCHAs
There are two main types of text CAPTCHAs that are solved differently:
1. Text Questions (Text CAPTCHA)
These are CAPTCHAs that contain a text question that needs to be answered. For example:
- "If tomorrow is Saturday, what day is today?"
- "What is 2 + 2?"
- "Type the word 'hello' backwards"
To solve such CAPTCHAs, use the text() method with the question text.
2. Image CAPTCHAs (Normal CAPTCHA / ImageToTextTask)
These are classic CAPTCHAs in the form of images with distorted text (letters, numbers, or a combination). The user must recognize and enter the text from the image.
To solve such CAPTCHAs, use the normal() method or ImageToTextTask with the image in Base64 format.
In this article, we will cover both types.
Solving Text Questions (Text CAPTCHA)
PHP
- Install the package:
Use Composer to install the library:
bash
composer require 2captcha/2captcha
- Configure the client:
php
require 'vendor/autoload.php';
use TwoCaptcha\TwoCaptcha;
$solver = new TwoCaptcha('YOUR_API_KEY');
- Solve the text CAPTCHA:
php
try {
$result = $solver->text([
'text' => 'If tomorrow is Saturday, what day is today?',
'lang' => 'en', // Optional: specify language
]);
echo 'CAPTCHA solved: ' . $result->code;
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
Python
- Install the package:
Use pip to install the library:
bash
pip install 2captcha-python
- Configure the client:
python
from twocaptcha import TwoCaptcha
solver = TwoCaptcha('YOUR_API_KEY')
- Solve the text CAPTCHA:
python
try:
result = solver.text('If tomorrow is Saturday, what day is today?', lang='en')
print('CAPTCHA solved:', result['code'])
except Exception as e:
print('Error:', e)
Go
- Install the package:
Use go get to install the library:
bash
go get -u github.com/2captcha/2captcha-go
- Configure the client:
go
package main
import (
"github.com/2captcha/2captcha-go"
)
func main() {
client := api2captcha.NewClient("YOUR_API_KEY")
// Additional configuration if needed
}
- Solve the text CAPTCHA:
go
package main
import (
"fmt"
"log"
"github.com/2captcha/2captcha-go"
)
func main() {
client := api2captcha.NewClient("YOUR_API_KEY")
cap := api2captcha.Text{
Text: "If tomorrow is Saturday, what day is today?",
Lang: "en", // Optional: specify language
}
code, err := client.Solve(cap.ToRequest())
if err != nil {
log.Fatal("Error:", err)
}
fmt.Println("CAPTCHA solved:", code)
}
C#
- Install the package:
Use NuGet to install the library:
powershell
Install-Package TwoCaptcha
- Configure the client:
csharp
using TwoCaptcha;
var solver = new TwoCaptcha("YOUR_API_KEY");
- Solve the text CAPTCHA:
csharp
using System;
using TwoCaptcha.Captcha;
class Program
{
static void Main()
{
var solver = new TwoCaptcha("YOUR_API_KEY");
var captcha = new Text
{
Text = "If tomorrow is Saturday, what day is today?",
Lang = "en" // Optional: specify language
};
try
{
solver.Solve(captcha).Wait();
Console.WriteLine("CAPTCHA solved: " + captcha.Code);
}
catch (AggregateException e)
{
Console.WriteLine("Error: " + e.InnerException.Message);
}
}
}
Java
- Install the package:
Add the dependency to your pom.xml:
xml
<dependency>
<groupId>com.github.2captcha</groupId>
<artifactId>2captcha-java</artifactId>
<version>1.0.0</version>
</dependency>
- Configure the client:
java
import com.twocaptcha.TwoCaptcha;
TwoCaptcha solver = new TwoCaptcha("YOUR_API_KEY");
- Solve the text CAPTCHA:
java
import com.twocaptcha.TwoCaptcha;
import com.twocaptcha.captcha.Text;
public class Main {
public static void main(String[] args) {
TwoCaptcha solver = new TwoCaptcha("YOUR_API_KEY");
Text captcha = new Text();
captcha.setText("If tomorrow is Saturday, what day is today?");
captcha.setLang("en"); // Optional: specify language
try {
solver.solve(captcha);
System.out.println("CAPTCHA solved: " + captcha.getCode());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
JavaScript (Node.js)
- Install the package:
Use npm to install the library:
bash
npm install @2captcha/captcha-solver
- Configure the client:
javascript
const { Solver } = require('@2captcha/captcha-solver');
const solver = new Solver('YOUR_API_KEY');
- Solve the text CAPTCHA:
javascript
(async () => {
try {
const result = await solver.text({
text: 'If tomorrow is Saturday, what day is today?',
lang: 'en' // Optional: specify language
});
console.log('CAPTCHA solved:', result);
} catch (error) {
console.error('Error:', error.message);
}
})();
Solving Image CAPTCHAs (Normal CAPTCHA / ImageToTextTask)
For CAPTCHAs in the form of images with distorted text, a different approach is used — the normal() method or ImageToTextTask task type.
The Solving Process
- Get the CAPTCHA image — via browser or HTTP request
- Encode to Base64 — for API transmission
- Submit the task — via the createTask endpoint
- Poll for the result — via getTaskResult
- Use the solution — enter the recognized text into the form
API Parameters
Required Parameters
| Parameter | Type | Description |
|---|---|---|
| type | string | Always "ImageToTextTask" |
| body | string | CAPTCHA image in Base64 format |
Optional but Recommended Parameters
| Parameter | Type | Description |
|---|---|---|
| numeric | integer | 0 — any characters (default), 1 — numbers only, 2 — letters only |
| case | boolean | true — respect letter case (highly recommended) |
| math | boolean | true — if the CAPTCHA requires calculating a math expression |
| minLength | integer | Minimum expected answer length |
| maxLength | integer | Maximum expected answer length |
| comment | string | Additional instructions for the workers |
| languagePool | string | Set to "ru" for Russian, "en" for English, etc. (optional) |
JSON Request Examples
Create Task Request
json
{
"clientKey": "YOUR_API_KEY",
"task": {
"type": "ImageToTextTask",
"body": "BASE64_ENCODED_IMAGE",
"case": true,
"numeric": 2,
"minLength": 4,
"maxLength": 6,
"comment": "Enter letters only, case-sensitive"
}
}
Get Task Result Request
json
{
"clientKey": "YOUR_API_KEY",
"taskId": "TASK_ID_FROM_CREATE_TASK"
}
Successful Response
json
{
"errorId": 0,
"status": "ready",
"solution": {
"text": "aBcDeF"
},
"cost": "0.0005",
"createTime": 1692808229,
"endTime": 1692808234
}
Code Examples for Image CAPTCHAs
Python (via requests)
python
import time
import requests
import base64
API_KEY = "YOUR_API_KEY"
API_HOST = "api.2captcha.com"
def solve_image_captcha(image_path):
# Convert to Base64
with open(image_path, "rb") as f:
captcha_base64 = base64.b64encode(f.read()).decode('utf-8')
# Create task
create_response = requests.post(
f"https://{API_HOST}/createTask",
json={
"clientKey": API_KEY,
"task": {
"type": "ImageToTextTask",
"body": captcha_base64,
"case": True,
"numeric": 2
}
}
)
task_id = create_response.json()["taskId"]
# Wait for result
while True:
time.sleep(3)
result_response = requests.post(
f"https://{API_HOST}/getTaskResult",
json={
"clientKey": API_KEY,
"taskId": task_id
}
)
result = result_response.json()
if result.get("status") == "ready":
return result["solution"]["text"]
elif result.get("errorId") != 0:
raise Exception(f"Error: {result.get('errorDescription')}")
# Usage
if __name__ == "__main__":
solution = solve_image_captcha("captcha.png")
print(f"Solution: {solution}")
Python (via Official SDK)
python
from twocaptcha import TwoCaptcha
solver = TwoCaptcha('YOUR_API_KEY')
try:
result = solver.normal(
'path/to/captcha.jpg',
case=True,
numeric=2
)
print(f"Solved: {result['code']}")
except Exception as e:
print(f"Error: {e}")
PHP
php
require 'vendor/autoload.php';
use TwoCaptcha\TwoCaptcha;
$solver = new TwoCaptcha('YOUR_API_KEY');
try {
$result = $solver->normal([
'file' => 'path/to/captcha.jpg',
'case' => true,
'numeric' => 2
]);
echo 'CAPTCHA solved: ' . $result->code;
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
JavaScript (Node.js)
javascript
const { Solver } = require('@2captcha/captcha-solver');
const solver = new Solver('YOUR_API_KEY');
(async () => {
try {
const result = await solver.normal({
file: 'path/to/captcha.jpg',
case: true,
numeric: 2
});
console.log('CAPTCHA solved:', result);
} catch (error) {
console.error('Error:', error.message);
}
})();
Selenium Integration
python
from selenium import webdriver
from selenium.webdriver.common.by import By
from twocaptcha import TwoCaptcha
import time
def solve_captcha_selenium(driver, api_key):
# Take a screenshot of the CAPTCHA element
captcha_element = driver.find_element(By.CSS_SELECTOR, ".captcha-image")
captcha_element.screenshot("temp_captcha.png")
# Solve via API
solver = TwoCaptcha(api_key)
result = solver.normal("temp_captcha.png", case=True)
captcha_text = result['code']
# Enter the solution
input_field = driver.find_element(By.ID, "captcha-input")
input_field.clear()
input_field.send_keys(captcha_text)
# Submit the form
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
time.sleep(2)
# Usage
driver = webdriver.Chrome()
try:
driver.get("https://example.com/login")
solve_captcha_selenium(driver, "YOUR_API_KEY")
finally:
driver.quit()
Best Practices
1. Enable Case Sensitivity
Most text CAPTCHAs are case-sensitive. Always set case: true to ensure the API returns the exact uppercase and lowercase letters required.
2. Specify Character Types
If you know the CAPTCHA contains only numbers, set numeric: 1. If it contains only letters, set numeric: 2. This prevents workers from confusing the number 0 with the letter O, or 1 with I.
3. Set Length Constraints
Providing minLength and maxLength helps workers verify their input. If a CAPTCHA always has 5 characters, setting both to 5 drastically reduces errors.
4. Provide Clear Instructions
Use the comment parameter to give specific hints. For example: "Letters only, no numbers" or "Math expression, calculate the result".
5. Implement Retry Logic
CAPTCHAs can sometimes be too distorted. If a solution is rejected by the target website, fetch a new CAPTCHA and try again.
python
def solve_with_retry(image_path, max_attempts=3):
for attempt in range(max_attempts):
try:
return solve_image_captcha(image_path)
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
time.sleep(2)
raise Exception("Failed to solve CAPTCHA after multiple attempts")
6. Check Image Quality
Ensure the image is clear, not cropped, and in a supported format (JPEG, PNG, GIF). The maximum file size is 100 KB.
Solution Accuracy Reports
If a CAPTCHA solution turns out to be incorrect or you want to report a correct solution, use the 2Captcha reporting system. This helps improve recognition quality and trains the workers.
When to Send Reports
Send reportIncorrect if:
- The recognized text does not match the CAPTCHA image
- The solution was rejected by the website
- The worker made an obvious mistake
Send reportCorrect if:
- The solution was correct but the system marked it as incorrect
- You want to confirm the high quality of the solution
Report Parameters
| Parameter | Type | Description |
|---|---|---|
| clientKey | string | Your API key |
| taskId | string | Task ID from createTask |
Example of Sending a Report
python
import requests
API_KEY = "YOUR_API_KEY"
API_HOST = "api.2captcha.com"
def report_incorrect(task_id):
"""Report an incorrect CAPTCHA solution"""
response = requests.post(
f"https://{API_HOST}/reportIncorrect",
json={
"clientKey": API_KEY,
"taskId": task_id
}
)
result = response.json()
if result.get("errorId") == 0:
print("Incorrect solution report accepted")
return True
else:
print(f"Error: {result.get('errorDescription')}")
return False
def report_correct(task_id):
"""Report a correct CAPTCHA solution"""
response = requests.post(
f"https://{API_HOST}/reportCorrect",
json={
"clientKey": API_KEY,
"taskId": task_id
}
)
result = response.json()
if result.get("errorId") == 0:
print("Correct solution report accepted")
return True
else:
print(f"Error: {result.get('errorDescription')}")
return False
Important Points for Reporting
- Send reports promptly — the faster you report an issue, the better
- Do not abuse reports — send them only when truly necessary
- Verify taskId — make sure you are using the correct task ID
- Save taskId — store task IDs in your application state for potential report submission
Troubleshooting Common Issues
Incorrect Recognition
Solutions:
- Enable
case: true - Specify the correct
numericvalue (1 for numbers, 2 for letters) - Add precise instructions in the
commentparameter - Improve the image quality before sending
Low Success Rate
Solutions:
- Use higher resolution images (avoid heavy compression)
- Add
minLengthandmaxLengthparameters - Verify you are using the correct API endpoint
- Check if the CAPTCHA requires a math calculation (set
math: true)
Timeouts
Solutions:
- Set a reasonable timeout in your polling loop (e.g., 60-120 seconds)
- Implement retry logic for edge cases
- Check your internet connection
- Ensure your account balance is sufficient
Conclusion
CAPTCHAs remain one of the biggest barriers when collecting data from open sources and hinder accessibility. Therefore, it is important to optimize bypass methods.
This article covered solving methods in different programming languages for both types of text CAPTCHAs:
- Text questions — use the
text()method with the question text - Image CAPTCHAs — use the
normal()method orImageToTextTaskwith the image in Base64
Key Takeaways:
- For text questions, use
solver.text()with thetextparameter - For image CAPTCHAs, use
solver.normal()with thebodyparameter (Base64) - Always enable
case: truefor image CAPTCHAs - Use
numeric,minLength, andmaxLengthto guide the workers - Implement
reportIncorrectandreportCorrectto maintain high solving quality - Handle errors gracefully with retry logic
Note that in each example, you need to replace 'YOUR_API_KEY' with your actual API key from the 2Captcha service. Additional information and usage examples can be found in the official 2Captcha documentation.
Useful Links
- API Documentation: https://2captcha.com/api-docs/normal-captcha
- GitHub Examples: https://github.com/2captcha
- Support Center: https://2captcha.com/support/tickets/new
- How to Submit Reports: https://2captcha.com/h/how-to-submit-reports
If you are interested in recognition solutions, such as systems for training models, you can contact us for additional information.