CAPTCHAFORUM
Administrator
https://2captcha.com/blog/captcha-bypass-in-selenium
Selenium is a powerful tool for automating web applications for testing and parsing. However, it can be challenging to bypass captcha checks in Selenium. A special recognition automation service is required to solve captchas automatically. 2Captcha is a captcha-solving service that can be integrated with Selenium to bypass captchas on any site.
How to bypass captcha with Selenium and 2Captcha
- Create an account on 2Captcha and add funds.
- Note the API key and site key of the captcha you want to solve.
- Install the following libraries: 2captcha-python, selenium, and webdriver-manager.
- Write a Python file where you write captcha-solving code.
- Write Selenium code to visit the target page and solve the captcha using 2Captcha.
Code:
from selenium.webdriver.common.by import By
from twocaptcha import TwoCaptcha
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
solver = TwoCaptcha('YOUR_API_KEY')
site_key = 'SITE_KEY'
options = webdriver.ChromeOptions()
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--disable-extensions')
options.add_argument('--disable-infobars')
options.add_argument('--disable-notifications')
options.add_argument('--disable-popup-blocking')
options.add_argument('--disable-save-password-bubble')
options.add_argument('--disable-translate')
options.add_argument('--disable-web-security')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--start-maximized')
driver = webdriver.Chrome(service=ChromeService(executable_path=ChromeDriverManager().install()), options=options)
driver.get('https://www.google.com/recaptcha/api2/demo')
iframe = driver.find_element(By.XPATH, '//iframe[@title="reCAPTCHA"]')
driver.switch_to.frame(iframe)
recaptcha = driver.find_element(By.XPATH, '//div[@class="rc-anchor rc-anchor-normal rc-anchor-light"]')
recaptcha.click()
result = solver.recaptcha(sitekey=site_key, url=driver.current_url)
driver.execute_script(f'document.getElementById("g-recaptcha-response").innerHTML="{result["code"]}";')
driver.execute_script('document.getElementById("recaptcha-demo-form").submit();')
driver.quit()