Selenium 认为按钮在禁用时可单击并引发 WebDriverException

Selenium thinks button is clickable when it's disabled and raises WebDriverException

我知道有人和我有同样的问题,但事实证明他使用的代码与我不同。 (我 NOT 对此有同样的问题:Selenium identifies the button as clickable when it wasn't)所以,显然我试图在每次按钮 无法点击时刷新页面或使用 WebDriverException 错误禁用

因此,每当 Selenium 抛出 WebDriverException 错误时,如果您尝试单击禁用的对象(如果我没记错的话),它就会刷新页面直到它被启用。它已经工作了几天,但由于某种原因我不知道我做了什么,它突然开始出现故障?。

它就像什么都没发生过一样,即使元素明显被禁用也不会抛出任何错误。我尝试打印变量只是为了检查元素是否实际存储在变量中。但是,它做到了。所以我不知道是什么导致了这个问题。我把代码放在下面,每一个有用的答案我都很感激!谢谢!

purchasenow = browser.find_element_by_xpath("/html/body/div[1]/div/div[2]/div[2]/div[2]/div[2]/div[3]/div/div[5]/div/div/button[2]")
purchasenow.click()
print(purchasenow)

while True:
    try:
        purchasenow.click()
        newtime()
        print("[INFO :] ORDER BUTTON ENABLED!, ATTEMPTING TO PUT ITEM IN CART...")
        webhook = DiscordWebhook(url=logs, content='[INFO :] ORDER BUTTON ENABLED!, ATTEMPTING TO PUT ITEM IN CART...')
        if withlogging == "y":
            response = webhook.execute()
        break
    except WebDriverException:
        newtime()
        print("[INFO :] ORDER BUTTON DISABLED!, REFRESHING THE PAGE...")
        webhook = DiscordWebhook(url=logs, content='[INFO :] ORDER BUTTON DISABLED!, REFRESHING THE PAGE...')
        if withlogging == "y":
            response = webhook.execute()
        browser.refresh()
        continue

编辑 [12/10/2020]:尝试使用 is_enabled() 来确保它,但不知何故它被检测为 True 或可点击。仍在寻找可能的解决方案,请在答案中告诉我!

多次刷新网页并不能确保元素在页面加载时立即变为可点击状态。现代网站越来越多地实施 JavaScript, ReactJS, jQuery, Ajax, Vue.js, Ember.js, GWT, etc. to render the dynamic elements within the DOM tree. Hence to invoke click() on a 有必要等待元素及其子元素完全呈现并成为 可交互


element_to_be_clickable()

element_to_be_clickable is the expectation for checking an element is visible and enabled such that you can click it. It is 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

理想情况下,要等待按钮可点击,您需要引入 WebDriverWait for the element_to_be_clickable() and you can use the following based :

WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div/div[2]/div[2]/div[2]/div[2]/div[3]/div/div[5]/div/div/button[2]"))).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 identifies the button as clickable when it wasn't
  • Get HTML source of WebElement in Selenium WebDriver using Python