Hey there, amazing automation enthusiasts! ๐๐
Have you ever been frustrated by those annoying reCAPTCHAs when trying to scrape websites or automate tasks? Well, guess what? I found the perfect solution using 2Captcha API and it's absolutely game-changing! ๐คฉ
When we're doing web scraping or automation, those pesky reCAPTCHAs always get in our way, right? But with 2Captcha API, we can make our bots act just like humans and bypass them completely! Today I'm going to share exactly how to do this using Python and Selenium - it's going to be so exciting! ๐ฏโจ
๐ What We're Going to Build Today! (Get Ready!)
Here's our super cool automation journey:
- Sign up with 2Captcha and grab our magical API key! ๐
- Use Python + Selenium to control our browser like a pro! ๐
- Solve reCAPTCHAs automatically with 2Captcha API magic! ๐
- Submit forms successfully and celebrate our victory! โ
Trust me, by the end of this, you'll feel like an automation wizard! Let's dive in! ๐ช
๐ Setting Up 2Captcha API (Your New Best Friend!)
๐น Step 1: Creating Your 2Captcha Account
First things first - let's get you set up with 2Captcha! It's like getting a VIP pass to the automation world! ๐ซ
# This is going to be our secret weapon! โจ
print("Welcome to the automation revolution! ๐ค๐")
๐น Step 2: Getting Your API Key (The Golden Ticket!)
Once you're logged in:
- Navigate to your shiny dashboard ๐
- Copy that precious API Key (we'll need this beauty for our script!) ๐
- Add some credits if you want to use the premium features ๐ฐ
And just like that, we're ready to rock! ๐ธโจ
๐ ๏ธ Installing Our Super Tools! (Library Party Time!)
Let's get all our awesome libraries installed! This is like assembling our superhero toolkit! ๐ช
pip install selenium requests webdriver-manager
๐ What Each Library Does (Meet the Team!):
- selenium โ Our browser automation superhero! ๐ฆธโโ๏ธ
- requests โ The communication expert for 2Captcha API! ๐ก
- webdriver-manager โ The helpful assistant that manages our drivers! ๐
Isn't it exciting how each tool has its own special power? ๐
๐๏ธ Opening the Target Website with Selenium! (Browser Magic!)
Let's start by opening our target website using Selenium. This is where the fun begins! ๐ช
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
# Launch our trusty Chrome browser! ๐
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Open the website with reCAPTCHA (our mission target! ๐ฏ)
driver.get("https://www.example.com")
time.sleep(3) # Give the page a moment to load - patience is key! โฐ
print("Browser launched successfully! Ready for action! ๐")
๐น What This Magical Code Does:
- Launches Chrome using Selenium like a pro! ๐ป
- Navigates to our target website - hello there, reCAPTCHA! ๐
- Waits 3 seconds for everything to load nicely ๐
So far so good! Our browser automation adventure has begun! ๐ฎ
๐ The Main Event: Solving reCAPTCHA with 2Captcha! (The Magic Happens!)
Now for the most exciting part - let's make our bot solve reCAPTCHAs automatically! This is pure magic! โจ๐ช
๐น Step 1: Finding the reCAPTCHA Site Key (Detective Work!)
Every reCAPTCHA has a unique site key - we need to find it first! ๐ต๏ธโโ๏ธ
# Let's hunt for that reCAPTCHA site key! ๐
try:
recaptcha_element = driver.find_element(By.XPATH, "//div[@class='g-recaptcha']")
recaptcha_sitekey = recaptcha_element.get_attribute("data-sitekey")
print(f"Found the secret key! ๐๏ธ: {recaptcha_sitekey}")
except Exception as e:
print(f"Oops! Couldn't find the reCAPTCHA: {e}")
# Alternative methods to find reCAPTCHA
recaptcha_sitekey = "your-site-key-here" # Fallback option!
๐น Step 2: Sending Our Request to 2Captcha (Calling for Backup!)
Time to ask 2Captcha to work their magic! This is like calling in the experts! ๐โจ
import requests
import json
# Our secret API credentials! ๐
API_KEY = "your_2captcha_api_key_here" # Replace with your actual key!
CAPTCHA_URL = "https://2captcha.com/in.php"
# Prepare our magical request payload! ๐ฆ
payload = {
"key": API_KEY,
"method": "userrecaptcha",
"googlekey": recaptcha_sitekey,
"pageurl": driver.current_url, # Current page URL
"json": 1
}
print("Sending reCAPTCHA to our AI helpers! ๐ค๐ซ")
# Send the request to 2Captcha! ๐
response = requests.post(CAPTCHA_URL, data=payload)
response_data = response.json()
if response_data["status"] == 1:
captcha_id = response_data["request"]
print(f"Success! Got captcha ID: {captcha_id} โจ")
else:
print(f"Oops! Error: {response_data}")
๐น Step 3: Waiting for the Solution (Patience, Young Padawan!)
Now we wait for 2Captcha to solve our reCAPTCHA. It's like waiting for a cake to bake! ๐ฐโฐ
# The anticipation is killing me! Let's check for our solution! ๐ฏ
token_url = f"https://2captcha.com/res.php?key={API_KEY}&action=get&id={captcha_id}&json=1"
print("Waiting for our AI heroes to solve the reCAPTCHA... ๐คโณ")
max_attempts = 24 # Maximum waiting time (about 2 minutes)
attempt = 0
while attempt < max_attempts:
print(f"Checking attempt {attempt + 1}... ๐")
token_response = requests.get(token_url)
token_data = token_response.json()
if token_data["status"] == 1:
recaptcha_token = token_data["request"]
print("๐ SUCCESS! We got our golden token! โจ")
print(f"Token: {recaptcha_token[:50]}...") # Show first 50 chars
break
elif token_data["request"] == "CAPCHA_NOT_READY":
print("Still working on it... โฐ")
time.sleep(5) # Wait 5 seconds before checking again
attempt += 1
else:
print(f"Unexpected response: {token_data}")
break
else:
print("Timeout! The reCAPTCHA took too long to solve ๐")
๐น Step 4: Injecting the Token (The Grand Finale!)
Now for the most satisfying part - injecting our solved token! ๐ชโจ
# Time to inject our precious token! ๐๐
try:
# Method 1: Direct injection into the textarea
print("Injecting token using Method 1... ๐งช")
driver.execute_script(f"""
document.getElementById('g-recaptcha-response').innerHTML = '{recaptcha_token}';
document.getElementById('g-recaptcha-response').style.display = 'block';
""")
# Method 2: Alternative approach for stubborn sites
print("Adding extra magic with Method 2... โจ")
driver.execute_script(f"""
document.querySelector('[name="g-recaptcha-response"]').value = '{recaptcha_token}';
""")
# Method 3: Trigger the callback if needed
print("Triggering callbacks... ๐")
driver.execute_script("""
if (typeof grecaptcha !== 'undefined' && grecaptcha.getResponse) {
console.log('reCAPTCHA callback triggered!');
}
""")
print("Token injection complete! ๐ฏโ
")
# Give it a moment to process
time.sleep(2)
except Exception as e:
print(f"Token injection failed: {e} ๐")
๐น Step 5: Submit the Form (Victory Dance Time!)
Finally, let's submit our form and celebrate our success! ๐
# Find and click that submit button! ๐ฏ
try:
# Common submit button selectors
submit_selectors = [
"input[type='submit']",
"button[type='submit']",
"#submit",
".submit",
"button:contains('Submit')"
]
submit_button = None
for selector in submit_selectors:
try:
if selector.startswith("#") or selector.startswith("."):
submit_button = driver.find_element(By.CSS_SELECTOR, selector)
else:
submit_button = driver.find_element(By.CSS_SELECTOR, selector)
break
except:
continue
if submit_button:
print("Found the submit button! Clicking now... ๐ฑ๏ธโจ")
submit_button.click()
# Wait for the page to respond
time.sleep(5)
# Check if we succeeded!
current_url = driver.current_url
page_source = driver.page_source.lower()
if "success" in page_source or "thank" in page_source:
print("๐๐ VICTORY! We successfully bypassed reCAPTCHA! ๐๐")
else:
print("Form submitted! Check the result manually! ๐")
else:
print("Couldn't find submit button - you might need to click manually! ๐คทโโ๏ธ")
except Exception as e:
print(f"Submit error: {e}")
๐จ Complete Automation Script (The Full Magic Spell!)
Here's our complete, beautiful automation script! Copy this and make it yours! ๐
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import requests
import time
import json
class RecaptchaSolver:
"""Our adorable reCAPTCHA solving class! ๐ค๐"""
def __init__(self, api_key):
self.api_key = api_key
self.driver = None
def setup_driver(self):
"""Initialize our browser! ๐"""
print("Setting up our automation browser... ๐๐จ")
service = Service(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# options.add_argument("--headless") # Uncomment for headless mode
self.driver = webdriver.Chrome(service=service, options=options)
print("Browser ready for action! โ
")
def get_site_key(self, url):
"""Navigate to site and extract reCAPTCHA key! ๐"""
print(f"Navigating to: {url} ๐งญ")
self.driver.get(url)
time.sleep(3)
try:
# Try multiple selectors
selectors = [
"//div[@class='g-recaptcha']",
"//div[@data-sitekey]",
"//iframe[contains(@src, 'recaptcha')]"
]
for selector in selectors:
try:
element = self.driver.find_element(By.XPATH, selector)
site_key = element.get_attribute("data-sitekey")
if site_key:
print(f"๐ฏ Found site key: {site_key[:20]}...")
return site_key
except:
continue
print("โ ๏ธ Couldn't auto-detect site key. Please provide manually!")
return None
except Exception as e:
print(f"Error finding site key: {e}")
return None
def solve_recaptcha(self, site_key, page_url):
"""Send reCAPTCHA to 2Captcha for solving! ๐ง โจ"""
print("Sending reCAPTCHA to our AI helpers... ๐ค๐ซ")
# Submit reCAPTCHA for solving
submit_url = "https://2captcha.com/in.php"
submit_data = {
"key": self.api_key,
"method": "userrecaptcha",
"googlekey": site_key,
"pageurl": page_url,
"json": 1
}
response = requests.post(submit_url, data=submit_data)
result = response.json()
if result["status"] != 1:
print(f"โ Error submitting reCAPTCHA: {result}")
return None
captcha_id = result["request"]
print(f"โ
reCAPTCHA submitted! ID: {captcha_id}")
# Wait for solution
return self.get_solution(captcha_id)
def get_solution(self, captcha_id):
"""Wait for and retrieve the solution! โฐโจ"""
print("Waiting for solution... โณ")
get_url = f"https://2captcha.com/res.php?key={self.api_key}&action=get&id={captcha_id}&json=1"
for attempt in range(24): # Wait up to 2 minutes
print(f"๐ Check #{attempt + 1}")
response = requests.get(get_url)
result = response.json()
if result["status"] == 1:
token = result["request"]
print("๐ Got our golden token! โจ")
return token
elif result["request"] == "CAPCHA_NOT_READY":
print("โฐ Still solving...")
time.sleep(5)
else:
print(f"โ ๏ธ Unexpected response: {result}")
return None
print("โ Timeout waiting for solution")
return None
def inject_token(self, token):
"""Inject the solved token! ๐๐"""
print("Injecting our precious token... ๐โจ")
try:
# Multiple injection methods for maximum compatibility!
injection_script = f"""
// Method 1: Direct textarea injection
var textarea = document.getElementById('g-recaptcha-response');
if (textarea) {{
textarea.innerHTML = '{token}';
textarea.style.display = 'block';
console.log('Method 1: Direct injection โ
');
}}
// Method 2: Query selector approach
var response = document.querySelector('[name="g-recaptcha-response"]');
if (response) {{
response.value = '{token}';
console.log('Method 2: Query selector โ
');
}}
// Method 3: Trigger callbacks
if (typeof grecaptcha !== 'undefined') {{
console.log('Method 3: Callbacks available โ
');
}}
console.log('Token injection complete! ๐ฏ');
"""
self.driver.execute_script(injection_script)
time.sleep(2)
print("โ
Token injected successfully!")
return True
except Exception as e:
print(f"โ Token injection failed: {e}")
return False
def submit_form(self):
"""Submit the form! ๐"""
print("Looking for submit button... ๐")
# Common submit button patterns
submit_patterns = [
("ID", "submit"),
("CSS_SELECTOR", "input[type='submit']"),
("CSS_SELECTOR", "button[type='submit']"),
("CSS_SELECTOR", ".submit"),
("CSS_SELECTOR", ".btn-submit"),
("XPATH", "//button[contains(text(), 'Submit')]"),
("XPATH", "//input[@value='Submit']")
]
for method, selector in submit_patterns:
try:
if method == "ID":
button = self.driver.find_element(By.ID, selector)
elif method == "CSS_SELECTOR":
button = self.driver.find_element(By.CSS_SELECTOR, selector)
elif method == "XPATH":
button = self.driver.find_element(By.XPATH, selector)
print(f"๐ฏ Found submit button using {method}!")
button.click()
time.sleep(3)
print("๐ Form submitted! Check the results! ๐")
return True
except Exception as e:
continue
print("โ ๏ธ Couldn't find submit button automatically")
return False
def cleanup(self):
"""Clean up resources! ๐งน"""
if self.driver:
self.driver.quit()
print("Browser closed! ๐")
# Usage example! ๐
def main():
"""Our main automation function! ๐ฏ"""
# Configuration
API_KEY = "YOUR_2CAPTCHA_API_KEY_HERE" # Replace with your key!
TARGET_URL = "https://example.com/form-with-recaptcha" # Replace with target!
# Initialize our solver
solver = RecaptchaSolver(API_KEY)
try:
# Step 1: Setup browser
solver.setup_driver()
# Step 2: Get site key
site_key = solver.get_site_key(TARGET_URL)
if not site_key:
site_key = input("Please enter the site key manually: ")
# Step 3: Solve reCAPTCHA
token = solver.solve_recaptcha(site_key, TARGET_URL)
if token:
# Step 4: Inject token
if solver.inject_token(token):
# Step 5: Submit form
solver.submit_form()
print("๐ Mission accomplished! ๐")
else:
print("โ Token injection failed")
else:
print("โ Failed to solve reCAPTCHA")
except Exception as e:
print(f"โ Error during automation: {e}")
finally:
# Always cleanup!
solver.cleanup()
if __name__ == "__main__":
print("๐ Starting reCAPTCHA automation adventure! ๐")
main()
๐ Success Celebration & What We Learned! (Victory Lap!)
Congratulations, amazing developer! You've just mastered the art of reCAPTCHA automation! ๐โจ
โ What We Accomplished:
- Mastered Selenium for browser automation like pros! ๐ฎ
- Integrated 2Captcha API for intelligent reCAPTCHA solving! ๐ง
- Built robust error handling for real-world scenarios! ๐ก๏ธ
- Created reusable automation code that you can use anywhere! ๐
๐ก Key Insights That'll Make You Shine:
- Patience is crucial - reCAPTCHA solving takes time! โฐ
- Multiple fallback methods ensure higher success rates! ๐ฏ
- Proper error handling makes automation reliable! ๐ช
- Clean code structure makes maintenance a breeze! ๐งน
๐ฎ What's Next? (The Adventure Continues!)
I'm already working on even cooler automation projects! Here's what's coming up:
- AI-powered CAPTCHA solving using computer vision! ๐๏ธ๐ค
- Advanced bot detection bypassing techniques! ๐ฅท
- Multi-threaded automation for super-fast processing! โก
- Cloud-based automation for scalable solutions! โ๏ธ
๐ Your Homework (If You're Feeling Adventurous!):
- Try different websites with your new skills! ๐
- Add proxy support for extra stealth! ๐ต๏ธโโ๏ธ
- Create a GUI interface for non-technical users! ๐ฅ๏ธ
- Experiment with different CAPTCHA types beyond reCAPTCHA! ๐งฉ
โ ๏ธ Important Ethical Reminder! (Use Your Powers Wisely!)
Remember, with great automation power comes great responsibility! ๐ฆธโโ๏ธ
Always use these techniques ethically:
- Respect website terms of service ๐
- Don't overwhelm servers with requests ๐ค
- Use for legitimate automation needs only โ
- Be a good digital citizen! ๐
๐ข Let's Connect and Build Together!
I'm so excited to hear about your automation adventures! Drop a comment and tell me:
- Which websites are you planning to automate? ๐ค
- What challenges are you facing with automation? ๐ช
- Any cool ideas for improving this script? ๐ก
Tags: #WebAutomation #Selenium #2Captcha #reCAPTCHA #PythonAutomation #WebScraping #BotDevelopment #AIAutomation
If this guide helped you break through those annoying reCAPTCHAs, please give it a LGTM๐ and let's revolutionize automation together! The future of web automation is so bright! ๐๐
P.S. Remember, every automation expert started with their first "Hello, World!" script. Keep experimenting, keep learning, and most importantly - keep having fun with code! You've got this! ๐ซ