Selenium将按钮标识为可点击,而它不是



我遇到了一个问题,Selenium说即使按钮被禁用也可以点击。

我正在将Selenium与一个网站一起使用,您必须首先选择一个日期,然后从下拉列表中选择一个时间段,然后才能单击"预订"按钮并实际执行任何操作。在选择日期和时间隙之前,按钮元素为

<div id="pt1:b2" class="x28o xfn p_AFDisabled p_AFTextOnly" style="width:300px;" _afrgrp="0" role="presentation"><a data-afr-fcs="false" class="xfp" aria-disabled="true" role="button"><span class="xfx">Book</span></a></div>

选择日期和时间槽后,按钮变为

<div id="pt1:b2" class="x28o xfn p_AFTextOnly" style="width:300px;" _afrgrp="0" role="presentation"><a href="#" onclick="this.focus();return false" data-afr-fcs="true" class="xfp" role="button"><span class="xfx">Book</span></a></div>

我正在尝试使用此代码来等待按钮可点击

wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.ID, 'pt1:b2')))

但Selenium表示,即使没有选择日期或时间段,该按钮在网站加载后几乎可以立即点击,并且按钮完全变灰且无法点击。我已经通过检查导航到 url 和等待按钮可单击后的时间戳来测试这一点,几乎没有延迟。我已经手动求助于尝试,除了循环和睡眠之间才能成功单击按钮,但宁愿找出导致此问题的原因。有什么想法吗?

通过搜索要更改的类属性而不是element_to_be_clickable来解决此问题。

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div[class='x28o xfn p_AFTextOnly']")))

element_to_be_clickable((

element_to_be_clickable是检查元素是否可见并启用以便您可以单击它的期望。它被定义为:

def element_to_be_clickable(locator):
""" An Expectation for checking an element is visible and enabled such that
you can click it."""
def _predicate(driver):
element = visibility_of_element_located(locator)(driver)
if element and element.is_enabled():
return element
else:
return False
return _predicate

现在,即使没有选择日期或时间段,网站也会加载,属性的值p_AFDisabled的存在决定了元素是启用还是禁用。接下来,当您填写日期或时隙时,属性的值p_AFDisabled将被删除,并且元素变为可单击

因此,理想情况下,要等待按钮可单击,您需要诱导WebDriverWaitelement_to_be_clickable(),您可以使用以下任一定位器策略:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.p_AFTextOnly > a[onclick] > span.xfx"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'p_AFTextOnly')]/a[@onclick]/span[text()='Book']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Selenium 可点击检查显示并启用以检查点击能力

并且 isdisplay 检查样式属性,但启用检查禁用的属性

现在禁用在大多数情况下不是通过html禁用属性处理,而是通过javascript和css类处理

因此,可点击条件在这些情况下不起作用

https://www.selenium.dev/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html

所以在这种情况下,点击不会引发错误

https://github.com/SeleniumHQ/selenium/blob/trunk/py/selenium/common/exceptions.py

如果检查异常类,您可以看到异常仅存在 不可见 ,单击拦截 ,未启用

最新更新