0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OMG! ๐Ÿค– AI ร— 2Captcha: I Completely Automated reCAPTCHA! ๐Ÿš€โœจ

Posted at

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:

  1. Sign up with 2Captcha and grab our magical API key! ๐Ÿ”‘
  2. Use Python + Selenium to control our browser like a pro! ๐ŸŒ
  3. Solve reCAPTCHAs automatically with 2Captcha API magic! ๐Ÿ”„
  4. 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!):

  1. Try different websites with your new skills! ๐ŸŒ
  2. Add proxy support for extra stealth! ๐Ÿ•ต๏ธโ€โ™€๏ธ
  3. Create a GUI interface for non-technical users! ๐Ÿ–ฅ๏ธ
  4. 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! ๐Ÿ’ซ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?