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

如何在每次循环运行时将索引自增1?(Python WebDriver场景)

解决循环中索引自增的问题

你需要单独维护索引变量,每次循环触发异常时让索引自增,再从列表中取对应元素。同时要加上索引越界判断,避免出现死循环或索引错误。修改后的代码如下:

# 初始化起始索引,从1开始
current_index = 1
# 获取列表最大索引,防止越界
max_index = len(categorylist) - 1

while True:
    try:
        # 尝试点击目标元素
        WebDriverWait(driver, 20, ignored_exceptions=(NoSuchElementException, StaleElementReferenceException)).until(
            EC.element_to_be_clickable((By.XPATH, f"//div[child::span[text()='{oddsnumber}'] and span[text()='{oddstype}']]"))
        ).click()
        # 找到目标元素后退出循环
        break
    except (NoSuchElementException, StaleElementReferenceException):
        # 检查索引是否超出列表范围
        if current_index > max_index:
            print("所有分类都已尝试,未找到目标元素")
            break
        # 取当前索引对应的分类值
        categoryindex = categorylist[current_index]
        # 点击当前分类元素
        WebDriverWait(driver, 20, ignored_exceptions=(NoSuchElementException, StaleElementReferenceException)).until(
            EC.element_to_be_clickable((By.XPATH, f"//div[text() ='{categoryindex}']"))
        ).click()
        # 索引自增1,为下一次循环做准备
        current_index += 1

关键修改说明:

  • 单独维护current_index变量,从1开始初始化,每次异常后自增
  • 添加max_index判断,避免索引超出列表长度导致IndexError
  • 明确指定捕获的异常类型,避免原代码中except:捕获所有异常的风险
  • 找到目标元素或遍历完所有分类后,用break退出循环,避免死循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:05:29