我正在使用硒,我需要定位元素列表中的第一和第二文本。
例如“标题1”和“标题2”。
<div class="this-list">
<div class="item">
<div class="title">Title 1</title>
</div>
<div class="item">
<div class="title">Title 2</title>
</div>
<div class="item">
<div class="title">Title 3</title>
</div>
</div>
<div class="not-this-list">
<div class="item">
<div class="title">Wrong Title 1</title>
</div>
<div class="item">
<div class="title">Wrong Title 2</title>
</div>
<div class="item">
<div class="title">Wrong Title 3</title>
</div>
</div>
“标题1”和“标题2”文本的xPath是什么
答案 0 :(得分:1)
选项1:
//div[@class='this-list']/div[@class='item']/div[@class='title' and normalize-space(text()='Title 1')]
选项2:
//div[@class='title'][text()[normalize-space() = 'Title 1']]
答案 1 :(得分:1)
使用position()
索引
(//div[@class='this-list']//div[@class='title'])[position()=1 or position()=2]
演示:
var xpath = "(//div[@class='this-list']//div[@class='title'])[position()=1 or position()=2]";
var xpathRes = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var matched = xpathRes.iterateNext();
while (matched) {
console.log(matched.textContent)
matched= xpathRes.iterateNext();
}
<div class="this-list">
<div class="item">
<div class="title">Title 1</div>
</div>
<div class="item">
<div class="title">Title 2</div>
</div>
<div class="item">
<div class="title">Title 3</div>
</div>
</div>
<div class="not-this-list">
<div class="item">
<div class="title">Wrong Title 1</div>
</div>
<div class="item">
<div class="title">Wrong Title 2</div>
</div>
<div class="item">
<div class="title">Wrong Title 3</div>
</div>
</div>