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

使用Selenium与ngWebDriver访问动态ng-repeat的技术问询

解决AngularJS动态ng-repeat列的自动化定位问题

我来帮你搞定这个AngularJS动态ng-repeat列的自动化操作定位问题!先拆解下你给的DOM片段里的核心信息:这个列是通过ng-repeat="column in sbCtrl.SlideboardStore.columns track by sbCtrl.getUniqueColumnId(column)"动态生成的,数组sbCtrl.SlideboardStore.columns的变化会直接影响列的数量和内容,所以常规的静态定位容易失效。下面给你几种实用的定位方案,适配不同的自动化工具场景:

  • 方案1:用CSS选择器直接定位(通用所有Selenium类工具)
    利用ng-repeat属性的特征来匹配,因为后面带了track by,所以用^=(匹配属性值开头)来忽略后面的部分:

    div[ng-repeat^="column in sbCtrl.SlideboardStore.columns"]
    

    如果要精准定位某一列,可以结合column-id属性(比如你DOM里的emptydata):

    div[column-id="emptydata"][ng-repeat^="column in sbCtrl.SlideboardStore.columns"]
    

    还能通过ng-class的状态筛选,比如找未折叠的列:

    div[ng-repeat^="column in sbCtrl.SlideboardStore.columns"]:not(.containCol__col__collapsed)
    
  • 方案2:用Protractor专属定位(针对AngularJS项目最优)
    如果你用的是Protractor(专门为Angular应用设计的自动化工具),可以直接用Angular内置的定位器,非常省心:

    // 获取所有动态列
    const columns = element.all(by.repeater('column in sbCtrl.SlideboardStore.columns'));
    
    // 按索引取第2列(索引从0开始)
    const targetColumn = columns.get(1);
    
    // 筛选column-id为emptydata的列
    const emptyDataColumn = columns.filter(col => {
      return col.getAttribute('column-id').then(id => id === 'emptydata');
    }).first();
    
  • 方案3:Selenium显式等待+定位(避免动态加载问题)
    用普通Selenium的话,一定要加显式等待,确保元素加载完成后再操作,以Python为例:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 等待所有动态列加载完成,最多等10秒
    wait = WebDriverWait(driver, 10)
    all_columns = wait.until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div[ng-repeat^="column in sbCtrl.SlideboardStore.columns"]'))
    )
    
    # 遍历列并操作,比如打印column-id
    for col in all_columns:
        print("Column ID:", col.get_attribute('column-id'))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:53:25