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

Python Selenium实现循环点击按钮直到页面新增表格后停止

解决方案:循环点击按钮直至指定表格出现

原代码的核心问题

  1. By.ID用法错误:By.ID是常量,正确传参格式为(By.ID, "tableID"),而非By.ID("tableID")。
  2. 异常未处理:driver.find_element()找不到元素时会抛出NoSuchElementException,不会返回布尔值,导致循环直接中断报错。

方案1:通过find_elements判断元素存在性

find_elements会返回匹配元素的列表,空列表在布尔判断中为False,可避免抛出异常:

from selenium.webdriver.common.by import By
import time

while not driver.find_elements(By.ID, "tableID"):
    submit_btn.click()
    # 添加短暂等待,避免高频点击导致页面卡顿
    time.sleep(0.5)

方案2:使用显式等待(官方推荐)

显式等待会在指定时间内轮询检查元素,比固定等待更高效,适合处理动态加载的元素:

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

while True:
    try:
        # 等待1秒,直到表格元素出现(超时时间可按需调整)
        WebDriverWait(driver, 1).until(
            EC.presence_of_element_located((By.ID, "tableID"))
        )
        break  # 找到元素后退出循环
    except:
        submit_btn.click()
        # 点击后等待页面响应
        time.sleep(0.3)

注意事项

  • 若点击按钮后页面会刷新,submit_btn可能失效,需每次循环重新定位按钮(比如在循环内用driver.find_element重新获取按钮)。
  • 等待时间可根据页面加载速度调整,避免过长或过短。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:10:32