首页 > 解决方案 > 在框架 Selenium Python 上找不到元素

问题描述

我正在尝试制作一个登录到我的帐户的机器人。

插入密码和用户名后,我让机器人使用此代码单击“我不是机器人 recaptcha”,它可以工作:

def _delay():
      time.sleep(randint(1,3))

frames = driver.find_elements_by_tag_name('iframe') 
driver.switch_to_frame(frames[0])    
recaptcha = driver.find_element_by_xpath('//*[@id="recaptcha-anchor"]/div[1]')
driver.execute_script("arguments[0].click();",recaptcha)  
_delay()

在此之后,它会打开图像 recaptcha。

现在,我想尝试使用音频到文本的方法,但我无法单击图像下的“音频”按钮。这是我使用的代码:

#finding the frame
driver.switch_to_default_content()
element_image = driver.find_element_by_xpath('/html/body')
element = element_image.find_elements_by_tag_name('iframe')
driver.switch_to_frame(element[0])

_delay()

#clicking on the "audio" button
button = driver.find_element_by_id('recaptcha-audio-button')  #error
driver.execute_script("arguments[0].click();",button)

这是输出:`发生异常:NoSuchElementException

我不知道如何单击“音频”按钮。这对我来说似乎是正确的,但仍然不起作用。有小费吗 ?`

标签: pythonseleniumrecaptchaframenosuchelementexception

解决方案


我怀疑这是因为您的delay()功能在页面元素可见之前完成。您可以尝试增加它暂停验证的时间长度,但更好的方法是重构它以使用 SeleniumWebDriverWait对象。

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
from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException

driver = webdriver.Firefox() # or chrome...
fluent_wait = WebDriverWait(driver, timeout=10, poll_frequency=1, 
                            ignored_exceptions=[ElementNotVisibleException, 
                                                ElementNotSelectableException])
elem = fluent_wait.until(expected_conditions.element_to_be_clickable((By.ID, "recaptcha-audio-button")))
if elem:
    driver.execute_script("arguments[0].click();",button)
else:
    print("couldn't find button")

推荐阅读