Python Selenium如何实现:优先点击指定元素,元素不存在时点击备选元素
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
tryblock runs first: if the primary element is found and clicked, the code moves on without touching theexceptblock. - If the primary element is missing, Selenium raises
NoSuchElementException, which we catch immediately. Then the code jumps to theexceptblock 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

