Home > Enterprise >  How to get a list within two different elements in selenium java
How to get a list within two different elements in selenium java

Time:01-06

Here, having two h3 tags under a div tag.Need a lists which is under 1st h3 tag(which is not under 2nd h3 tag)

As shown in the below image,
h3(1) -> v2-43-october-11--2022
h3(2) -> v2-45-january-10--2023 Under h3(1) i have two list(ul), under h3(2) i have one list(ul) Need an elements which is under h3(1) only
(https://i.stack.imgur.com/So4A4.png)

Here is my code

List<WebElement> logs = driver.findElements(By.xpath("//*[@id=\"on-premisesbackwardsincompatible\"]/following-sibling::h3[1]/following-sibling::ul"));
for(WebElement w : logs)
       System.out.println(w.getText());

but it's giving all the 3 lists, need 1st two lists only
Need an elements which is under h3(1) only
(https://i.stack.imgur.com/XCs1W.png)

CodePudding user response:

Here You are providing indexing to the h3 tag, after which both the lists are getting located because both are coming in following-sibling Axes.

You can provide indexing to ul direclty as: List logs = driver.findElements(By.xpath("//*[@id="on-premisesbackwardsincompatible"]/following-sibling::h3/following-sibling::ul[1]"));

or you can locate the element with xpath: List logs = driver.findElements(By.xpath("//*[@id='v2-43-october-11--2022']/following-sibling::ul[1]));

CodePudding user response:

You can try the below XPath:

//*[@id='v2-45-january-10--2023']/preceding-sibling::ul

It gives the results of the first 2 <ul> tags which are next to the first <h3> tag.

  • Related