Select 包含两个跨度文本的元素
Select a element that contains two span text
<label class=‘Fruit’>
<span class=‘name’>Apple</span>
<span class=‘price’>23</span>
</label>
<label class=‘Fruit’>
<span class=‘name’>Apple</span>
<span class=‘price’>56</span>
</label>
我正在使用 Selenium
编写自动化脚本。目前,我在将 xPath
写入 select 第一个标签时遇到问题。但是,这两个标签具有相同的 class 名称,并且其跨度的 class 名称也相同。只是价格不同。在这种情况下,我如何 select 第一个元素?
您可以使用如下匹配号码,
- 至select第一个元素:
//label[@class='‘Fruit’'][1]
- 到select第二个元素:
//label[@class='‘Fruit’'][2]
当你需要select基于Fruit name
和Price
的label
时,你需要写一个自定义的xPath
到select第一个标签:
//label//span[text()='Apple']//following-sibling::span[text()='23']//parent::label
或
//label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
到select第二个标签:
//label//span[text()='Apple']//following-sibling::span[text()='56']//parent::label
或
//label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
这里有一个例子。
<!DOCTYPE html>
<html>
<body>
<div>
<p class="intro">23</p>
<p class="intro">11</p>
</div>
<div>
<p class="intro">27</p>
<p class="intro">11</p>
</div>
<p id="demo"></p>
<script>
const x = document.getElementsByClassName("intro");
for (let i = 0; i < 2; i++) {
if(x[i].innerHTML == "23"){
var obj = x[i].parentElement;
}
}
obj.style.backgroundColor = "red";
</script>
</body>
</html>
<label class=‘Fruit’>
<span class=‘name’>Apple</span>
<span class=‘price’>23</span>
</label>
<label class=‘Fruit’>
<span class=‘name’>Apple</span>
<span class=‘price’>56</span>
</label>
我正在使用 Selenium
编写自动化脚本。目前,我在将 xPath
写入 select 第一个标签时遇到问题。但是,这两个标签具有相同的 class 名称,并且其跨度的 class 名称也相同。只是价格不同。在这种情况下,我如何 select 第一个元素?
您可以使用如下匹配号码,
- 至select第一个元素:
//label[@class='‘Fruit’'][1]
- 到select第二个元素:
//label[@class='‘Fruit’'][2]
当你需要select基于Fruit name
和Price
label
时,你需要写一个自定义的xPath
到select第一个标签:
//label//span[text()='Apple']//following-sibling::span[text()='23']//parent::label
或
//label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
到select第二个标签:
//label//span[text()='Apple']//following-sibling::span[text()='56']//parent::label
或
//label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
这里有一个例子。
<!DOCTYPE html>
<html>
<body>
<div>
<p class="intro">23</p>
<p class="intro">11</p>
</div>
<div>
<p class="intro">27</p>
<p class="intro">11</p>
</div>
<p id="demo"></p>
<script>
const x = document.getElementsByClassName("intro");
for (let i = 0; i < 2; i++) {
if(x[i].innerHTML == "23"){
var obj = x[i].parentElement;
}
}
obj.style.backgroundColor = "red";
</script>
</body>
</html>