selenium.common.exceptions.ElementNotVisibleException:消息:元素不可交互,显式等待不能使用Selenium和Python

问题描述 投票:2回答:3

我试图访问PenFed以获得我目前的未付金额。我做了很多研究,不幸的是,我仍然难过。我正在使用Python Selenium,我试图点击侧面的初始登录按钮以查看用户名字段。这是元素的HTML代码:

<a href="https://www.penfed.org/" class="pfui-button-login login-slide-button pfui-button pfui-btn-tertiary-dark-blue-outline" id="mobile-login" data-di-id="#mobile-login">Login</a>

当我尝试运行以下代码时:

driver.find_element_by_id("mobile-login").click()

我收到以下错误:

selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable

即使我尝试使用WebDriver等功能,例如:

try:
    WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.ID, "mobile-login"))).click()
except ElementNotVisibleException:
    WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.ID, "mobile-login"))).click()

无论我让他们等多久,我都收到一条超时消息:

raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:

我的所有研究都说调用等待函数应该修复它但它对我不起作用。我还读到,在点击按钮之前我可能必须调用元素顶部的图像覆盖,但我也没有在网站代码中看到任何内容。如果我正在测试它,我能够通过代码单击按钮的唯一方法是,如果我首先点击它,所以我不知道我可以使用的任何其他东西。提前感谢您的帮助!

更新:我发现以下代码适用于我:

element = driver.find_element_by_id("mobile-login")
driver.execute_script("$(arguments[0]).click();", element)

但我不知道execute_script实际上做了什么。有人可以解释这段代码是否有效或者是否有其他替代方案适合他们?

python selenium selenium-webdriver css-selectors webdriverwait
3个回答
0
投票

您指定的代码是JQueryexecute_script(p1, p2)运行一个js脚本,其中p1是脚本(在您的情况下是单击元素的JQuery行),p2是所需的元素。如果arguments[0]等于“元素”,你似乎不应该需要p2,但我不完全确定。

一个可能的解决方法是使用计数器来查看单击元素的次数。如果计数器达到一定数量并且页面没有改变(您可以通过在当前页面上找到唯一元素/值来检查),那么您就知道它不可点击。

祝好运!


-1
投票

所需元素是一个动态元素,因此要定位您必须引入WebDriverWait元素以使元素可单击,您可以使用以下解决方案:

  • 代码块: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument('start-maximized') options.add_argument('--disable-extensions') driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe') driver.get('https://www.penfed.org/') WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.pfui-button.login-slide-button.pfui-button-login.dtm-global-nav[data-id='Open Log In Drawer']"))).click()
  • 浏览器快照:

penfed.org


-1
投票

您尝试单击的链接是针对移动网站的,如果您以桌面分辨率查看该网站,则该链接不可见。如果缩小浏览器直到更改布局,您将看到与该链接对应的LOGIN按钮。这就是你获得ElementNotVisibleException的原因。

对于你的第二个问题,使用.execute_script()的原因是它直接执行JS并且可以点击任何东西......隐藏或不隐藏。 Selenium旨在以用户身份与页面进行交互,因此它不会让您单击不可见元素等。如果您打算让脚本像用户一样行事,您将希望避免使用.execute_script(),因为它允许您在页面上做一些用户不能做的事情。

如果您想像桌面用户那样登录,则需要使用下面的CSS选择器单击“登录”按钮

button[data-id='Open Log In Drawer']

这将打开一个侧面板,您可以在其中输入您的用户名等并登录。仅供参考...您可能需要等待,以便在继续登录过程之前让面板有机会打开。

© www.soinside.com 2019 - 2024. All rights reserved.