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

Python Selenium遍历网页按钮时属性获取异常及跳转后无法循环问题

问题修复方案

1. print输出None的问题修复

你调用get_attribute时参数拼写错误,误写为onlick(缺少字母c),修正为正确的属性名onclick即可正常输出:

print(ele.get_attribute("onclick"))

2. 无法遍历剩余按钮的问题修复

根因

点击第一个按钮后页面发生跳转/刷新,初始查询得到的eleButtons列表中存储的DOM元素引用全部失效(Selenium中称为陈旧元素引用异常),即使返回原页面,原有引用也无法对应新渲染的DOM元素,因此无法继续遍历。

解决方案

你的按钮onclick属性仅Select$N的序号部分有差异,可先统计总按钮数,再按序号逐次定位按钮,每次返回列表页后重新获取元素即可规避陈旧元素问题。

修复后代码示例

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

# 先获取按钮总数量
btn_xpath = "//input[@type='button' and contains(@onclick,'ctl00$ContentPlaceHolder1$GridView2')]"
total_buttons = len(driver.find_elements(By.XPATH, btn_xpath))

# 按序号循环操作,序号从1匹配你的HTML规则
for idx in range(1, total_buttons + 1):
    # 等待列表页按钮加载完成,重新定位当前序号的按钮
    current_btn = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, f"{btn_xpath} and contains(@onclick,'Select${idx}')"))
    )
    # 打印属性验证
    print(current_btn.get_attribute("onclick"))
    # 点击按钮,也可以直接用JS触发更稳定:
    # driver.execute_script(f"__doPostBack('ctl00$ContentPlaceHolder1$GridView2','Select${idx}')")
    current_btn.click()

    # 等待跳转后页面加载完成,可替换为你自己的页面加载判断逻辑
    time.sleep(2)

    # 返回按钮列表页
    driver.execute_script("document.getElementById('ctl00_ContentPlaceHolder1_Button2').click()")

    # 等待列表页加载完成
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, btn_xpath))
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:36:01