如何用 Selenium 检测 MtCaptcha 验证码?

问题描述 投票:0回答:1

我需要一些帮助。

在我使用 Selenium 模块的 Python 代码中,Selenium 无法识别网站

https://top-serveurs.net/gta/vote/midnight-rp
上的标识符mtcap-image-1。 我想知道是否有可能让 Selenium 识别 MtCaptcha 验证码,或者我是否需要为此使用另一个模块。

导致问题的行是:

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

Selenium 无法找到 ID

mtcap-image-1
。 我也尝试过使用 XPATH 和 CSS 选择器,但也没有用。

python bots recaptcha captcha
1个回答
0
投票

问题的原因是您尝试检索的

mtcap-image-1
元素位于名为
mtcaptcha-iframe-1
的 iframe 中。因此,在您检索元素之前,您首先需要使用以下方法切换到此 iframe:

# 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)

在测试答案中提供的代码时,我还意识到该页面在加载页面时打开了一个 cookie 同意弹出窗口,这可能会导致问题。要绕过它,您可以使用以下代码:

# 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()

现在为了完整起见,我用来解决您的代码问题的完整代码:

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"]')))
© www.soinside.com 2019 - 2024. All rights reserved.