我无法使用硒中的文本选择以下h2元素-
<h2>
<span id="presentations:0:categoryHeaderForm:j_idt95"><a id="presentations:0:categoryHeaderForm:j_idt95:j_idt97" href="#" class="ui-commandlink ui-widget chekChartLink" aria-label="Technical Information" onclick="PrimeFaces.ab({source:'presentations:0:categoryHeaderForm:j_idt95:j_idt97',process:'presentations:0:categoryHeaderForm:j_idt95:j_idt97',update:'chekChartForm',oncomplete:function(xhr,status,args){chekChartWidget.show();}});return false;" title="Technical Information">
<span class="icon-border icon-large icon-wrench"></span></a>
</span>Water Pump
<div id="presentations:0:categoryHeaderForm:j_idt101" class="ui-datalist ui-widget service-tsbs">
<div id="presentations:0:categoryHeaderForm:j_idt101_content" class="ui-datalist-content ui-widget-content"></div>
</div>
<script id="presentations:0:categoryHeaderForm:j_idt101_s" type="text/javascript">PrimeFaces.cw('DataList','widget_presentations_0_categoryHeaderForm_j_idt101',{id:'presentations:0:categoryHeaderForm:j_idt101'});</script>
</h2>
我尝试过:
driver.findElement(By.xpath("//h2[contains(text(), 'Water Pump')]"));
但得到:
org.openqa.selenium.NoSuchElementException:无法找到具有xpath的元素
有什么建议吗?
答案 0 :(得分:2)
您应该指定子文本节点的索引,该索引应包含必需的子字符串,例如//h2[contains(text()[2], 'Water Pump')]
或尝试通过作为字符串表示形式一部分的文本选择标题:
//h2[contains(., 'Water Pump')]
答案 1 :(得分:0)
您可以像这样在xpath中使用通配符*
和following-sibling::
:
driver.findElement(By.xpath("//h2[contains(text()[2], 'Water Pump')]/following-sibling::*"));
这里是this link中的一个示例。
希望这对您有帮助!
Ps。
@Path归功于@Anderson ...请参阅评论