我使用Java Selenium 2.0。这是我的HTML元素,它包含注释和回复注释:
<div class="comment-list">
<div class="comment">
<a class="content">Comment 1</a>
<div class="reply-comment">
<div class="comment">
<a class="content">Comment 1.1</a>
</div>
<div class="comment">
<a class="content">Comment 1.2</a>
</div>
</div>
</div>
<div class="comment">
<a class="content">Comment 2</a>
</div>
</div>
如何在评论中选择内容但没有回复评论? 这是预期的结果:
- Comment 1
- Comment 2
注意:我不想使用绝对的css选择器,例如:
comment-list > comment > content
解决!这是我的解决方案:
// Mark reply comments with a class "is-reply-comment"
JavascriptExecutor js = (JavascriptExecutor) driver;
List<WebElement> replyCommentElements = driver.findElements(By.cssSelector(".reply-comment .comment"));
for (WebElement replyCommentElement : replyCommentElements) {
js.executeScript("arguments[0].className += ' is-reply-comment'", replyCommentElement);
}
// Find comments except comments were marked "is-reply-comment"
List<WebElement> parentCommentElements = driver.findElements(By.cssSelector(".comment:not(.is-reply-comment)")
答案 0 :(得分:2)
您可以使用XPath
//div[not(@class='reply-comment')]/div/a[@class='content']
但这与CSS选择器
的差别不大div.comment-list > div.comment > a.content
但CSS选择器更快,浏览器支持更好,并且在浏览器之间比XPath更一致地实现。
答案 1 :(得分:0)