python - 在框架 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
我不知道如何单击“音频”按钮。这对我来说似乎是正确的,但仍然不起作用。有小费吗 ?`
解决方案
我怀疑这是因为您的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")
推荐阅读
- c# - 如何从 dotnet 核心 Web API 文件夹结构之外使用 ILogger?
- android - Android:提高地理围栏的准确性
- azure - 设置-AzVMCustomScriptExtension 是否成功?
- google-bigquery - 是否可以在 python 客户端中调用 BigQuery 程序?
- python-3.x - 为什么选择不同的数据类型会产生不同的结果?
- azure-devops - 如何开始修改所有 Azure 数据工厂触发器
- python - 合并具有相同范围但不同空间分辨率的 xarray 数据集
- snowflake-cloud-data-platform - 如何在雪花中启用 MFA
- firebase - 在部署 index.ts 时,全局范围内的 firebase 函数调用只需要字符串文字
- validation - 我们是否应该使用来自训练数据(Keras 中的 LSTM)的相同参数来规范化验证集和测试数据集?