硒将按钮识别为可点击

时间:2020-07-01 18:44:00

标签: python selenium selenium-webdriver webdriverwait expected-condition

我遇到一个问题,即Selenium表示即使禁用了按钮也可以单击。

我在一个网站上使用Selenium,您必须先选择一个日期,然后从下拉列表中选择时隙,然后才能单击“ Book”按钮,并且实际上可以执行任何操作。在选择日期和时隙之前,按钮元素为

<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之后等待按钮可单击之后的时间戳进行了测试,并且几乎没有延迟。我手动尝试了一次tryexcept循环,并在两者之间进行睡眠,以便能够成功单击按钮,但宁愿找出导致此问题的原因。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

仅通过搜索要更改的class属性而不是element_to_be_clickable即可解决此问题。

struct HomeView: View {
    @ObservedObject var instance: Instance
    var body: some View {
        Text(self.instance.status.text)
    }
}

答案 1 :(得分:0)

显示硒可点击检查并启用它来检查点击能力

isdisplay检查样式属性,而isenabled检查禁用属性

在大多数情况下,现在禁用不是通过html disable属性处理,而是通过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

如果检查异常类,则可以看到只有不可见的异常存在,单击拦截并没有启用

答案 2 :(得分:0)

element_to_be_clickable()

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

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
    

现在,即使在没有选择日期或时隙的情况下加载网站时, class 属性的值p_AFDisabled的存在也会确定该元素是否已启用 disabled 。接下来,当您填写日期或时间段时,将删除 class 属性的值p_AFDisabled,并且该元素将变为 clickable

因此,理想情况下,要等待按钮可单击,您需要为element_to_be_clickable()引入WebDriverWait,并且可以使用以下Locator Strategies中的任何一个:

  • 使用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