You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium如何实现:优先点击指定元素,元素不存在时点击备选元素

Handle NoSuchElementException with Fallback Click in Selenium Python

Got it, let's fix this issue where you need to click one element first, and fall back to another if the first doesn't exist. The key here is to use Python's try-except block to catch the NoSuchElementException that's thrown when the first element can't be located.

Step 1: Import Required Modules

First, make sure you've imported the necessary classes and exceptions. For modern Selenium versions (4+), we recommend using the By class instead of the old find_element_by_xpath method (which is now marked as deprecated):

from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

Step 2: Implement the Try-Except Logic

Wrap your primary click attempt in a try block. If the first element isn't found, the NoSuchElementException will trigger the except block where you execute the fallback click:

try:
    # First, attempt to click your target element
    driver.find_element(By.XPATH, "/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[1]").click()
except NoSuchElementException:
    # If the first element doesn't exist, click the fallback one
    driver.find_element(By.XPATH, "/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[2]").click()

Why This Works

  • The try block runs first: if the primary element is found and clicked, the code moves on without touching the except block.
  • If the primary element is missing, Selenium raises NoSuchElementException, which we catch immediately. Then the code jumps to the except block to click the second element.

Optional: Handle Edge Case for Fallback Element

If there's a chance the second element might also be missing, you can add another layer of try-except inside the except block, or pre-check for its existence. But for your stated use case, the above code should work perfectly.

For Older Selenium Versions

If you're still using an older version and prefer the deprecated find_element_by_xpath method, the logic is nearly identical:

from selenium.common.exceptions import NoSuchElementException

try:
    driver.find_element_by_xpath("/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[1]").click()
except NoSuchElementException:
    driver.find_element_by_xpath("/html/body/div[24]/div[1]/div/div/div[3]/div[1]/div/button[2]").click()

Just note that these old methods will be removed in future releases, so migrating to the By class approach is better for long-term code maintenance.

内容的提问来源于stack exchange,提问作者paitakht_pc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:37:28