Selenium认为按钮被禁用时是可点击的,并引发WebDriverException

2024-05-04 11:00:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道还有其他人和我有同样的问题,但事实证明他和我使用的代码不同。(我不是有同样的问题: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]:尝试通过启用()来确保它,但不知何故它被检测为真或可单击。仍在寻找可能的解决方案,请在答案中告诉我


Tags: 答案代码divinfo元素selenium错误order
1条回答
网友
1楼 · 发布于 2024-05-04 11:00:22

多次刷新网页无法确保该元素在页面加载时立即可点击。现代网站越来越多地实现JavaScriptReactJSjQueryAjaxVue.jsEmber.jsGWT等,以呈现DOM tree中的动态元素。因此,要在WebElement上调用click(),必须等待元素及其子元素完全呈现并成为可交互的


元素可点击()

^{}是检查元素是否可见并启用以便可以单击它的期望值。它是{a11}作为:

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

因此,理想情况下,要等待按钮可点击,您需要为element_to_be_clickable()引入WebDriverWait,并且可以使用以下基于Locator Strategy

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

参考资料

您可以在以下内容中找到一些相关的详细讨论:

相关问题 更多 >