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

如何通过唯一文本高效使用XPath获取div及关联label的ID

问题描述

我尝试多种方法获取目标div的ID,但因存在多个同类元素及重复ID,始终无法精准高效获取所需ID。尝试过的方法如下:

// 方法1
divId = driver.findElement(By.xpath("(//div[@data-activity-type='CompatCheck'])")).getAttribute("id");

// 方法2
divId = driver.findElement(By.xpath("(//div[@data-activity-type='CompatCheck'])[2]")).getAttribute("id");

// 方法3
driver.findElement(By.xpath("//div[@data-activity-type='CompatCheck'] and contains(.,'AndroidTesting')]")).getAttribute("id"));

对应的HTML结构:

<div> 
    <strong>Reena</strong>: 
    <label id="compatcheck_label">
        <em class="Highlight" style="padding: 1px; box-shadow: rgb(229, 229, 229) 1px 1px; border-radius: 3px; background-color: rgb(0, 191, 255); color: rgb(0, 0, 0); font-style: inherit;" match="test" loopnumber="472046515">Test</em>device testing - AndroidTesting
    </label>
</div>
<div>
    <span style="float: none;" class="special-apps-list">(Special Tag)</span>
    <label id="label_1100"></label>                            
    <span style="float: none;">0d 4h 39m 49s</span>
</div>
<div id="div_1100" data-activity-type="CompatCheck" class="mainActivity">
</div>

观察到目标div的ID(div_1100)与关联label的ID(label_1100)后缀一致,且“device testing - AndroidTesting”是唯一固定标识文本,想知道是否能通过该文本获取这两个ID,期望输出:

label_1100
div_1100
解决方案

完全可以通过这个唯一文本标识精准定位两个目标元素,核心是利用元素的层级和位置关系,从唯一文本所在元素出发,定位到关联的label和div:

分步实现(Java + Selenium)

// 1. 定位包含唯一文本的label元素
WebElement textLabel = driver.findElement(By.xpath("//label[contains(., 'device testing - AndroidTesting')]"));

// 2. 获取关联的label_1100:回到父div,选择下一个同级div内的label
String labelId = textLabel.findElement(By.xpath("../following-sibling::div[1]/label")).getAttribute("id");

// 3. 获取目标div_1100:从关联label的父div,选择下一个同级div
String divId = textLabel.findElement(By.xpath("../following-sibling::div[2]")).getAttribute("id");

// 输出结果
System.out.println(labelId);
System.out.println(divId);

直接定位的XPath写法

如果想简化代码,也可以用单条XPath直接获取两个元素的ID:

  • 获取label_1100:
String labelId = driver.findElement(By.xpath("//label[contains(., 'device testing - AndroidTesting')]/../following-sibling::div[1]/label")).getAttribute("id");
  • 获取div_1100:
String divId = driver.findElement(By.xpath("//label[contains(., 'device testing - AndroidTesting')]/../following-sibling::div[2]")).getAttribute("id");

关键逻辑说明

  • contains(., 'xxx'):匹配元素内包含指定文本(包括子元素的文本内容),避免因文本被<em>标签包裹导致定位失败;
  • ../:回到当前元素的父节点;
  • following-sibling::div[n]:选择当前节点之后的第n个同级div元素,确保定位不会被其他元素干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:01:34