以下是HTML代码:
<div class="table">
<div class="thead">
</div>
<div class="tbody grey-line">
<div class="trow">
<div class="tcell left" data-header-val="stuffa">
<div class="in-line-header">HEADER A</div>
<span id="idImlookingfor-0-0" class="asdf-asset
asdf-text">text1</span>
</div>
<div class="tcell right" data-header-val="stuffb">
</div>
<div class="trow">
<div class="tcell left" data-header-val="stuffc">
<div class="in-line-header">HEADER A</div>
<span id="idImlookingfor-1-0" class="asdf-asset
asdf-text">text2</span>
</div>
<div class="tcell right" data-header-val="stuffd">
</div>
</div>
</div>
以下是我用来尝试查找文字值的硒代码:
WebElement baseTable = driver.findElement(By.xpath("//div[@class='table']"));
List<WebElement> tableRows = baseTable.findElements(By.className("trow"));
WebElement rowEntry1 = tableRows.get(0);
WebElement rowEntry2 = tableRows.get(1);
WebElement tcellLeft1 = rowEntry1.findElement(By.className("tcell"));
WebElement tcellLeft2 = rowEntry2.findElement(By.className("tcell"));
WebElement text1 = tcellLeft1.findElement(By.xpath("//span[contains(@id, 'idImlookingfor')]"));
WebElement text2 = tcellLeft2.findElement(By.xpath("//span[contains(@id, 'idImlookingfor')]"));
System.out.println("ENTRY 1");
System.out.println(tcellLeft1.getAttribute("innerHTML"));
System.out.println("OUTPUT " + text1.getText());
System.out.println("ENTRY 2");
System.out.println(tcellLeft2.getAttribute("innerHTML"));
System.out.println("OUTPUT " + text2.getText());
这是我得到的输出:
ENTRY 1
<div class="in-line-header">HEADER A</div>
<span id="form-idImlookingfor-0-0" class="asdf-asset
asdf-text">text1</span>
OUTPUT text1
ENTRY 2
<div class="in-line-header">HEADER A</div>
<span id="form-idImlookingfor-1-0" class="asdf-asset
asdf-text">text2</span>
OUTPUT text1
我尝试搜索多行以获取相同的部分ID。为什么第二个条目给我&#34; text1&#34;这里。它应该是从父元素中找到元素。
答案 0 :(得分:0)
对于两个元素和两个与选择器匹配的元素,选择器相同时,您可能不希望此行为符合预期。在findElement()
中,提供唯一选择器以识别元素非常重要。随着
WebElement text1 = tcellLeft1.findElement(By.xpath("//span[contains(@id, 'idImlookingfor')]"));
WebElement text2 = tcellLeft2.findElement(By.xpath("//span[contains(@id, 'idImlookingfor')]"));
您实质上是针对两个元素,而您的选择器对于任何这些预期元素都不是唯一的。
在这种情况下,如果那是静态的,我会使用基于文本的xpath搜索。如
//span[text()='text1']
代表第一个元素。