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"]')))