Python Selenium中element_to_be_clickable多元素OR条件实现求助
在Python Selenium中实现多按钮的OR条件等待点击
问题原因
你之前的写法存在两个关键错误:
- 用Python的
or运算符拼接XPath完全无效,"/html/body/button[1]" or "/html/body/button[2]"在Python中会直接返回第一个非空字符串,相当于只传入了第一个XPath。 - 即使在XPath表达式里写
/html/body/button[1] or /html/body/button[2],*element_to_be_clickable*也只会等待单个元素,无法确保返回的是当前可点击的那个。
可行解决方案
方案1:使用EC.any_of组合等待条件
这是最简洁的实现方式,*EC.any_of*会等待任意一个传入的条件满足,返回第一个符合要求的元素。
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException import random while True: try: button = WebDriverWait(window, timeout=random.randint(5, 10), poll_frequency=0.2).until( EC.any_of( EC.element_to_be_clickable((By.XPATH, "/html/body/button[1]")), EC.element_to_be_clickable((By.XPATH, "/html/body/button[2]")) ) ) button.click() break except TimeoutException: window.refresh()
方案2:自定义等待条件
如果需要更灵活的逻辑,可以自定义一个等待函数,遍历所有目标XPath,检查哪个元素可点击。
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException import random def any_element_clickable(driver, xpaths): for xpath in xpaths: try: if EC.element_to_be_clickable((By.XPATH, xpath))(driver): return driver.find_element(By.XPATH, xpath) except: continue return False while True: try: button = WebDriverWait(window, timeout=random.randint(5, 10), poll_frequency=0.2).until( lambda driver: any_element_clickable(driver, ["/html/body/button[1]", "/html/body/button[2]"]) ) button.click() break except TimeoutException: window.refresh()
方案3:优化XPath表达式
用XPath的|运算符同时选中两个按钮,先等待元素存在,再遍历找到可点击的那个。
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException import random while True: try: # 等待两个按钮至少存在一个 buttons = WebDriverWait(window, timeout=random.randint(5, 10), poll_frequency=0.2).until( EC.presence_of_all_elements_located((By.XPATH, "/html/body/button[1] | /html/body/button[2]")) ) # 遍历找到第一个可点击的按钮 for btn in buttons: if btn.is_enabled() and btn.is_displayed(): btn.click() break break except TimeoutException: window.refresh()
内容的提问来源于stack exchange,提问作者jagiel95
相关产品推荐
相关产品推荐

