Home > Back-end >  how to add the second css selector xpath where the same element appears more than once
how to add the second css selector xpath where the same element appears more than once

Time:09-23

how to add the second css selector or xpath where the same element appears more than once.

WebElement element = driver.findElement(By.cssSelector("span.mat-content"));

I need to add the same css selector again but for the 2nd element how do it do that.

This is for the first one which I have added as seen above:

HTML:

<span class="mat-content ng-tns-c143-2587"> = first one

HTML which I need to add -

<span class="mat-content ng-tns-c143-2589"> = How do I add the css selector using this html tag.

WebElement element2 = driver.findElement(By.cssSelector("span.mat-content")); = In this place how do I add it for the second element

CodePudding user response:

List<WebElement> elements= driver.findElements(By.cssSelector("span.mat- 
content"));
WebElement element2 = elements.get(1); 

Should work

CodePudding user response:

If this span.mat-content represent multiple web element in HTMLDOM.

You can use findElements to grab them all.

List<WebElement> elements = driver.findElements(By.cssSelector("span.mat-content"));

Now elements is a list in Java-Selenium bindings.

You could do, elements.get(1) and this shall represent the second web element.

or You can iterate the entire list like this:

for (WebElement element : elements){
    element.getText(); //Note that each `element` is a web web element. 
}

If you do not wish to have the above way. You can try xpath indexing.

(//span[contains(@class,'span.mat-content')])[1]

should represent the first element.

and

(//span[contains(@class,'span.mat-content')])[2]

should represent the second element and so on..

[3], [4], .... [n]

just replace css with xpath. xpath indexing is not preferred choice.

  • Related