首页 > 解决方案 > 使用 Selenium 提取父元素的属性值

问题描述

有 Java 经验,对 Selenium、定位器等非常陌生。

深埋在一些 HTML 中的是几个类似的部门:

<div tabgroup="topTabs__County Summary" sectiongroup class="field TextDescription tab">
  <label for="request_48543">
    <span class="label">Monument</span>
  </label>
</div>
<div tabgroup="topTabs__County Summary" sectiongroup class="field DropDownList readonly tab">
  <label for="request_48543">
    <span class="label">Geolocation</span>
  </label>
</div>
<div tabgroup="topTabs__County Summary" sectiongroup class="field SingleLineText tab">
  <label for="request_48543">
    <span class="label">Intersection</span>
  </label>
</div

我需要一些 Selenium 魔法来找到具有特定值的标签,然后回溯以找到该标签的分区并从该分区中提取给定属性的值。向下钻取似乎相当容易,但如何“备份”?

例如,给定“地理位置”,我想提取“字段 DropDownList 只读选项卡”

我试过像

WebElement chill = m.findElement(By.xpath("../..//span[text='Geolocation']"));

无济于事

标签: javaselenium-webdrivertestng

解决方案


你颠倒了去父元素的顺序,你需要()text. xpath应该是

"//span[text()='Geolocation']/../.."

另一种选择是寻找一个带有“地理位置”文本的元素

"//div[.//span[text()='Geolocation']]"

这可能会给您更多结果,具体取决于不在问题中的 html 结构。在这种情况下,您可以添加唯一属性,例如tabgroup

"//div[.//span[text()='Geolocation']][@tabgroup]"

这将只返回<div>具有tabgroup属性的标签。

提取数据getAttribute("class")使用chill WebElement


推荐阅读