【发布时间】:2015-08-13 01:10:40
【问题描述】:
我想使用WebElement.findElement() API 使用 XPATH //span[@class='child-class'] 在父节点内定位节点。我认为这会将父级内部的<div> 返回给我。但是,它返回给我的是它在整个 DOM 树中找到的第一个。我是否使用了错误的 XPATH?
我也尝试使用.//span[@class='child-class'] 作为 XPATH,但这确实会返回任何内容。
谢谢。
更新:
鉴于下面的 HTML,我想为子标题 <span> 和子日期 <span> 定义一个定位器,并使用 WebElement.findElement() API 定位它们,而不管父级是 "//a/li [1]" 或 "//a/li[2]"
<a>
<li> parent 1
<div>
<span class="child-title child-style">title 1</span>
<span class="child-date child-style"> date 1</span>
<span class="child-author">author 1</span>
</div>
</li>
</a>
<a>
<li> parent 2
<div>
<span class="child-title child-style">title 2</span>
<span class="child-date child-style"> date 2</span>
<span class="child-author">author 3</span>
</div>
</li>
</a>
<a>
<li> parent 3
<div>
<span class="child-title child-style">title 3</span>
<span class="child-date child-style"> date 3</span>
<span class="child-author">author 3</span>
</div>
</li>
</a>
我有一个使用"//a/li[2]" 初始化和定位的WebElement parent2,
WebElement child = parent2.findElement(By.xpath("//span[@class='child-author']")); 会给我“作者 1”
WebElement child = parent2.findElement(By.xpath("span[@class='child-author']")); 会给我NoSuchElementException
【问题讨论】:
-
好的,经过你的编辑,这个问题是无稽之谈!您在问题中引用的大多数 XPath 都不存在于您提供的示例 HTML 中。任何地方都没有
//span[@class='child-class'],任何地方都没有//a/li[2]。这实际上可以解释NoSuchElementException。