How to detect a MtCaptcha captcha with Selenium?

Question:

I need some help.

In my Python code using the Selenium module, the identifier mtcap-image-1 on the website https://top-serveurs.net/gta/vote/midnight-rp is not recognized by Selenium.
I would like to know if it is possible to make Selenium recognize a MtCaptcha captcha or if I need to use another module for this.

The line causing the issue is:

captcha_img = driver.find_element(By.ID, "mtcap-image-1").

Selenium is unable to find the ID mtcap-image-1.
I have also tried with XPATH and CSS selectors, but it did not work either.

Asked By: eVerK0Z

||

Answers:

The cause of the issue is that the mtcap-image-1 element you are trying to retrieve is within an iframe called mtcaptcha-iframe-1. So before you can retrieve the element you first need to switch into this iframe using:

# Wait for the mtcaptache iframe to be available and switch into the iframe
iframe = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "mtcaptcha-iframe-1"))
)
driver.switch_to.frame(iframe)

While testing the code provided in the answer I also realized that the page is opening a cookie consent popup when loading the page which might cause issues down the line. To bypass it you can use the following code:

# Bypass cookie popup by clicking on accept button
popup = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, "/html/body/div[7]/div[2]/div[1]/div[2]/div[2]/button[1]/p"))
)
popup.click()

Now for completeness the full code I used to solve the issue with your code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC



# Define the driver and navigate to the captcha page
driver = webdriver.Chrome()
driver.get('https://top-serveurs.net/gta/vote/midnight-rp')

# Bypass cookie popup by clicking on accept button
popup = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, "/html/body/div[7]/div[2]/div[1]/div[2]/div[2]/button[1]/p"))
)
popup.click()

# Wait for the mtcaptache iframe to be available and switch into the iframe
iframe = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "mtcaptcha-iframe-1"))
)
driver.switch_to.frame(iframe)

# Wait for the captcha to load and obtain element in captcha_img variable
captcha_img = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="mtcap-image-1"]')))
Answered By: Henry Wills
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.