List of WebElements by Selenium and Java

4.5k Views Asked by At

I am get the elements of a tag from below part of HTML.

<div id="Ad-2details">
    <div class="H3">
        <a id=...></a>
        <a id=...></a>
        <a id=...></a>"

And my part of source code is;

WebElement element = driver.findElement(By.id("AD-2details"));
List<WebElement> elementList = element.findElements(By.className("H3"));

This code work correctly on old version of Selenium, but current version(4.1.2) make exception as;

Command: [3e995689fe46b9177a7a7821e9a6e59d, findChildElements {id=0.37748117883484866-1, using=class, value=H3}]

Question: Current version of Selenium does not get data from above type HTML? If no, how can I get data from above type HTML?

1

There are 1 best solutions below

1
On

As per the HTML:

<div id="Ad-2details">
    <div class="H3">
        <a id=...></a>
        <a id=...></a>
        <a id=...></a>

this line of code:

findElements(By.className("H3");

would always identify the only <div> node with class="H3"

Hence, you find only a single list entry as:

[3e995689fe46b9177a7a7821e9a6e59d, findChildElements {id=0.37748117883484866-1, using=class, value=H3}]

Solution

To get all the <a> tag elements you need to reach till the <a> tag and you can use either of the following locator strategies:

  • Using cssSelector:

    WebElement element = driver.findElement(By.id("AD-2details"));
    List<WebElement> elementList = element.findElements(By.cssSelector("div.H3 a"));
    
  • Using xpath:

    WebElement element = driver.findElement(By.id("AD-2details"));
    List<WebElement> elementList = element.findElements(By.xpath(".//div[@class='H3']//a"));
    

In a single line:

  • Using cssSelector:

    List<WebElement> elementList = element.findElements(By.cssSelector("div#Ad-2details div.H3 a"));
    
  • Using xpath:

    List<WebElement> elementList = element.findElements(By.xpath("//div[@id='Ad-2details']/div[@class='H3']//a"));