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

如何在Python Selenium中用IF语句处理两种按钮选择逻辑

实现Selenium根据元素存在性自动点击对应按钮

核心思路

Selenium找不到目标元素时会抛出NoSuchElementException,我们可以通过try-except捕获这个异常,或者用find_elements判断元素是否存在,以此区分两种场景,自动执行对应的点击操作,避免程序崩溃。

具体实现步骤

1. 先完成序列号输入(基础操作)

先写好输入产品序列号的基础代码,示例如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化浏览器
driver = webdriver.Chrome()
driver.get("你的登录页面URL")

# 输入序列号(替换成你页面实际的输入框定位方式)
serial_input = driver.find_element(By.ID, "serial_input")  # 假设输入框ID为serial_input
serial_input.send_keys("你的产品序列号")

2. 两种场景的判断逻辑

方法一:用try-except捕获异常(新手推荐)

先尝试查找“序列号已使用”对应的按钮,找到就点击;如果找不到(抛出异常),则点击未使用场景对应的按钮:

try:
    # 替换成你页面中"继续"按钮的实际XPath/定位方式
    used_btn = driver.find_element(By.XPATH, "//button[contains(text(),'继续')]")
    used_btn.click()
    print("序列号已使用,点击继续按钮")
except NoSuchElementException:
    # 替换成你页面中未使用场景按钮的实际定位方式
    unused_btn = driver.find_element(By.XPATH, "//button[contains(text(),'确认激活')]")
    unused_btn.click()
    print("序列号未使用,点击确认按钮")

方法二:用find_elements判断元素是否存在

find_elements会返回符合条件的元素列表,列表长度大于0说明元素存在:

# 查找已使用场景的按钮列表
used_btns = driver.find_elements(By.XPATH, "//button[contains(text(),'继续')]")
if len(used_btns) > 0:
    used_btns[0].click()
    print("序列号已使用,点击继续按钮")
else:
    # 查找未使用场景的按钮
    unused_btn = driver.find_element(By.XPATH, "//button[contains(text(),'确认激活')]")
    unused_btn.click()
    print("序列号未使用,点击确认按钮")

3. 优化:加入显式等待(避免页面加载延迟误判)

页面加载可能有延迟,直接查找元素容易因为元素未加载完成导致误判,用显式等待更稳定:

wait = WebDriverWait(driver, 10)  # 最多等待10秒

try:
    # 等待已使用场景的按钮可点击,超时则进入未使用分支
    used_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'继续')]")))
    used_btn.click()
    print("序列号已使用,点击继续按钮")
except:
    # 等待未使用场景的按钮可点击并点击
    unused_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'确认激活')]")))
    unused_btn.click()
    print("序列号未使用,点击确认按钮")

注意事项

  • 代码中的XPath/定位方式需要替换成你页面的实际元素定位(可通过浏览器F12开发者工具获取)
  • 也可以用元素的ID、class属性来定位,比如By.ID, "continue_btn",不一定非要用XPath
  • 程序结束后记得关闭浏览器:driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:55:13