I am trying to get child element (Card Number) from an html codes where html tags and class names are same. Below is the html code snippet
<li >
<li >
<div >
<span >Name: </span>
<span > VISA</span>
<p>
<span >Number:</span>
<span > ************4305</span>
</p>
<p>
<span >Expiry:</span>
<span > 03/2030</span>
</p>
</div>
</li>
<li >
<div >
<span >Name: </span>
<span > VISA</span>
<p>
<span >Number:</span>
<span > ************4111</span>
</p>
<p>
<span >Expiry:</span>
<span > 04/2031</span>
</p>
</div>
</li>
</li>
Below is the identifiers I tried. But both returned first card number "************4305".
@FindBy(xpath = "//li[@class='paymentMethods-stored']//li[@class='paymentMethod']")
private WebElement firstSavedCard;
@FindBy(xpath = "(//li[@class='paymentMethods-stored']//li[@class='paymentMethod'])[2]")
private WebElement secondSavedCard;
String firstCard=firstSavedCard.findElement(By.xpath("//*[@class='stored-card-details']/p[1]/span[2]")).getText();
String secondCard=secondSavedCard.findElement(By.xpath("//*[@class='stored-card-details']/p[1]/span[2]")).getText();
Other options tried: this also returned first card number "************4305".
secondSavedCard.findElement(By.xpath("/p[1]/span[2]")).getText();
secondSavedCard.findElement(By.xpath(".//*[@class='stored-card-details']/p[1]/span[2]")).getText()
CodePudding user response:
Try the below xpath
to select all the numbered tag -
//li[@]/descendant::span[4]
For selecting first element use -
(//li[@]/descendant::span[4])[1]
for selecting second element use -
(//li[@]/descendant::span[4])[2]
and so on.
Moreover you can use findelements
instead of findelement
which will find all the elements. Collect all the elements in a list and then iterate over and extract the text.
CodePudding user response:
The use of "//"
at the start of the XPATH will always look at the root of the DOM and ignore the fact you have called "findElement"
in the context of a parent element.
Using ".//"
should fix this so you may want to double check that.
Alternatively, you can use "self::*"
as a more verbose and obvious way