首页 > 解决方案 > 如何循环直到元素可点击

问题描述

我正在使用 python selenium chrome 驱动程序,我被困在这个问题上。

我怎样才能循环这段代码,直到其中一个元素是可点击的?

就像它最终可以点击一样,它应该被点击并打印(“可点击”),如果它仍然不可点击,它应该打印(“不可点击”)

WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//BUTTON[@type='submit'[text()='Zum Warenkorb hinzufügen']"))).click()
WebDriverWait(driver, 150).until(EC.element_to_be_clickable((By.CLASS_NAME, "c-modal__content")))

标签: pythonseleniumgoogle-chromeselenium-chromedriverpython-webbrowser

解决方案


我不确定您对大写按钮的使用是否正确。使用与 html 中相同的语法。

还有一件事:用 text() 检查你的 xpath:它应该是://button[@type='submit' and text()='Zum Warenkorb hinzufügen']

此外,在一个元素的情况下,这种循环的一般情况是:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

wait = WebDriverWait(driver, 15)
while True:
    try:
        element = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@type='submit' and text()='Zum Warenkorb hinzufügen']")))
        print("clickable")
        element.click()
    except TimeoutException:
        break

推荐阅读