Home > Software engineering >  Selenium webdriver read taking too long
Selenium webdriver read taking too long

Time:11-14

I'm opening a discord channel and busy looping reading messages from it with the below statement to get the elements:

List<org.openqa.WebElement> ret = driver.findElement(By.tagName("main")) // driver = WebDriver
            .findElements(By.tagName("li"))
            .stream()
            .filter(message -> message.getAttribute("id") != null
                    && message.getAttribute("id").contains("chat-messages"))
            .toList();

There are about 40 messages by default shown on the page, and it takes 5-6 seconds for every read. It is unacceptably long. I read that when there are no matches, findElements has an implicit wait time, but that is not the case here as there are elements returned in every read. Any idea what is causing this delay and how to improve it?

Update: From the first answer I received, I tried

List<WebElement> ret = driver.findElements(By.xpath("//main//li[contains(@id,'chat-messages')]"));

At first it appeared like it was fast but soon I realized it must have been some temporary thing. It is taking just as long as before.

CodePudding user response:

List<WebElement> ret = driver.findElements(By.xpath("//main//li[contains(@id,'chat-messages')]"));

Rather than retrieving the elements one at a time it helps to let xpath do the work and retrieve them all in one call.

CodePudding user response:

Try what results and performance you get with cssSelector.

Something like this:

List<WebElement> elements = driver.findElements(By.cssSelector("main [id^=chat-message]"));

or even without main

List<WebElement> elements = driver.findElements(By.cssSelector("[id^=chat-message]"));
  • Related