我的页面中有以下 HTML。
<div dojoattachpoint="rowNode" class="dijitTreeRow dijitTreeRowSelected" wairole="presentation" dojoattachevent="onmouseenter:_onMouseEnter, onmouseleave:_onMouseLeave, onclick:_onClick, ondblclick:_onDblClick" role="presentation" title="" style="padding-left: 19px; ">
<img src="/runtime/explorer.sharedresources/javascript-1.7.22.268034/release/dojo/resources/blank.gif" alt="" dojoattachpoint="expandoNode" class="dijitTreeExpando dijitTreeExpandoLeaf" wairole="presentation" role="presentation"/>
<span dojoattachpoint="expandoNodeText" class="dijitExpandoText" wairole="presentation" role="presentation">*</span>
<span dojoattachpoint="contentNode" class="dijitTreeContent" wairole="presentation" role="presentation">
<img src="/runtime/explorer.sharedresources/javascript-1.7.22.268034/release/dojo/resources/blank.gif" alt="" dojoattachpoint="iconNode" class="dijitIcon dijitTreeIcon criterionFolder" wairole="presentation" role="presentation"/>
<span dojoattachpoint="labelNode" class="dijitTreeLabel" wairole="treeitem" tabindex="-1" waistate="selected-false" dojoattachevent="onfocus:_onLabelFocus" role="treeitem" aria-selected="true">**My TEXT**</span>
</span>
</div>
这是正确识别元素的代码。
List<WebElement> RowNodesList = elementPopup.findElements(By.xpath("//div[@dojoattachpoint =\"rowNode\"]"));
for(WebElement RowNode:RowNodesList)
{
System.out.println("Left Padding: " + RowNode.getAttribute("style"));
System.out.println("Is Row Node Displayed: " + RowNode.isDisplayed());
WebElement labelNode = RowNode.findElement(By.xpath("//span[@dojoattachpoint=\"labelNode\"]"));
boolean IsNodeDisplayed = labelNode.isDisplayed();
System.out.println("Is Label Node Displayed: " + IsNodeDisplayed);
String NodeLabel = (String) ((JavascriptExecutor) _driver).executeScript("return arguments[0].firstChild.nodeValue",labelNode);
System.out.println("Row label From javaScript: " + NodeLabel);
System.out.println("Row label: " + labelNode.getText());
System.out.println("Row Class: " + labelNode.getAttribute("class"));
}
这是从代码生成的输出。
Left Padding: PADDING-LEFT: 19px
Is Row Node Displayed: true
Is Label Node Displayed: false
Row label From javaScript: undefined
Row label:
Row Class: dijitTreeLabel
出于某种原因,.getText() 返回一个空字符串。有任何想法吗?提前致谢。
编辑:奇怪的是,labelNode.isdisplayed() 返回 false,即使它在页面上可见。
编辑 2:我已将我的 OP 编辑到上述内容,以使问题更加清晰。因此,我想要的文本位于标签节点的 SPAN 标记中,它是 RowNode 的子节点。RowNode 应该显示,但标签节点没有。我认为这就是 LabelNode 的 .getText() 返回空字符串的原因。
有没有其他方法可以获取文本?
编辑3:我发现了问题。它是 xpath 搜索字符串。代替
WebElement labelNode = RowNode.findElement(By.xpath("//span[@dojoattachpoint=\"labelNode\"]"));
xpath 需要更改为
WebElement labelNode = RowNode.findElement(By.xpath(".//span[@dojoattachpoint=\"labelNode\"]"));
我曾假设“//”将指示 WebDriver 在当前上下文中查看。但显然,它在整个体内搜索(这不直观),并返回找到的第一个隐藏的元素。添加“.//”指示它在当前上下文(RowNode)中搜索。
感谢大家的帮助。