Selenium get only 1 in multi elements need to collect

41 Views Asked by At

as the question means, the driver->findElements just get 1 div.classnameA but the inspector show 22 .classnameA items. I also pause the process, using Thread.sleep(15) waiting for page full load because the AJAX request. So Kotlin lines so simple.

System.setProperty("webdriver.chrome.driver","src/main/kotlin/org/drivers/chromedriver")
val driver = ChromeDriver()
driver.get("https://somethingcool.com")
try {
   Thread.sleep(10000)
} finally {
  var e = driver.findElements(By.cssSelector(".classnameA"))
  println(e.size)
}

the interesting thing is, if I change to findElement with .classnameB, it returns all 5 elements on the page.

1

There are 1 best solutions below

2
attila-fazekas On

A couple of things regarding the shared code:

  1. From Selenium version 4.6, you don't need to manage browser binaries anymore. Please see this link for more information. So you can remove the first line.

  2. In general, Thread.sleep() calls for waiting for elements are discouraged, and you should use one of the Selenium waits - preferably explicit wait. Please see this link for more information.

Having said that, assuming the provided locator is correct, you can do something like this in Kotlin:

var wait: Wait<WebDriver> = FluentWait(driver)
    .withTimear wait: Wait<WebDriver> = FluentWait(driver)
    .without(Duration.ofSeconds(10))
    .pollingEvery(Duration.ofSeconds(1))
    .ignoring(NoSuchElementException::class.java)

var elements: List<WebElement> = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector(".classnameA")))

You can also try e.g. numberOfElementsToBe or other methods to wait for the elements as well.

If the code still fails to find elements, I suggest trying out a different locator strategy, e.g. className.