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

Selenium操作时禁用状态button仍响应点击,如何保持首循环直至按钮不可用

Selenium禁用按钮仍被点击问题解决方案

问题根因

原有代码仅捕获了NoSuchElementException元素不存在异常,但按钮处于disabled状态时元素本身仍可被定位到,不会触发异常,因此会直接执行点击操作。

修复代码

while True:
    try:
        in_the_cart = bw.find_element_by_xpath('//*[@id="product_page_detail"]/div[2]/div[10]/form/section/div/button')
        # 判断按钮是否处于启用状态
        if in_the_cart.is_enabled():
            in_the_cart.click()
            break
        print('buttonDisabled')
        time.sleep(5)
    except NoSuchElementException:
        print('buttonNotExist')
        time.sleep(5)

逻辑说明

  • 使用WebElement内置的is_enabled()方法可直接识别按钮的禁用状态,只有按钮处于可交互状态时才会执行点击并跳出循环
  • 元素不存在、元素禁用两种场景都会留在循环内持续等待,符合需求
  • 如果按钮禁用是通过自定义class、属性实现的,可将判断逻辑替换为if 'disabled' not in in_the_cart.get_attribute('class')等自定义规则适配页面场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:36:01