<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>
I am writing the automation script using Selenium
. Currently, I am facing a problem in writing xPath
to select the first label. However, these two label have same class name and the class name of its span is also the same. Only the price is different. In this situation, how can I select the first element?
CodePudding user response:
You can use match numbers like below,
- To select the first element:
//label[@class='‘Fruit’'][1]
- To select the second element:
//label[@class='‘Fruit’'][2]
You need to write a customized xPath
when you need to select the label
based on Fruit name
and Price
To select the first label:
//label//span[text()='Apple']//following-sibling::span[text()='23']//parent::label
or
//label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
To select the second label:
//label//span[text()='Apple']//following-sibling::span[text()='56']//parent::label
or
//label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
CodePudding user response:
here's an example.
<!DOCTYPE html>
<html>
<body>
<div>
<p >23</p>
<p >11</p>
</div>
<div>
<p >27</p>
<p >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>