使用Python Selenium时首个元素不可点击如何点击第二个元素
问题核心修正
你代码中使用的is_not_clicked()并非Selenium WebElement的原生方法,无法正确判断元素是否可点击。你需要先判断第一个按钮的可交互状态,再决定是否点击第二个备选按钮,以下是两种可用的实现方案:
方案1:基础属性判断实现
直接读取元素的可见、可交互属性做判断,同时兼容第一个元素不存在的场景:
from selenium.common.exceptions import NoSuchElementException try: # 定位第一个按钮 first_btn = self.driver.find_element(By.CSS_SELECTOR, ".estimator-container:nth-child(3) .btn") # 可点击条件:元素可见 + 处于可交互状态 if first_btn.is_displayed() and first_btn.is_enabled(): first_btn.click() else: # 第一个不可点击,点击第二个备选按钮 self.driver.find_element(By.LINK_TEXT, "Dont have the Plate?").click() except NoSuchElementException: # 第一个元素未定位到,直接点击第二个按钮 self.driver.find_element(By.LINK_TEXT, "Dont have the Plate?").click()
方案2:显式等待稳定实现
适配页面动态加载场景,避免元素还未渲染完成就做判断导致的误判:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException # 初始化等待对象,最长等待10秒 wait = WebDriverWait(self.driver, 10) try: # 等待第一个元素可点击,成功则直接点击 first_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".estimator-container:nth-child(3) .btn"))) first_btn.click() except TimeoutException: # 等待超时说明第一个元素不可点击,点击第二个备选按钮 second_btn = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Dont have the Plate?"))) second_btn.click()
补充注意事项
- 如果第二个元素的文本定位容易因为内容变化失效,可以替换为CSS_SELECTOR或XPATH定位,稳定性更高
- 如果出现元素被遮挡无法点击的报错,可以在点击前执行滚动逻辑,把元素滚动到可视区域:
self.driver.execute_script("arguments[0].scrollIntoView();", target_element) - 特殊场景下原生点击失效,可以用JS强制触发点击:
self.driver.execute_script("arguments[0].click();", target_element)
内容的提问来源于stack exchange,提问作者Enea Hysa
相关产品推荐
相关产品推荐

