The Java Selenium ChromeDriver experiences delays when loading a new page

I am currently working on a script that automates the login process on a website and performs certain actions. The code for logging in is as follows:

WebDriver driver;
JavascriptExecutor exec;

String dni = "...";
String passwd = "...";

driver = new ChromeDriver();
exec = (JavascriptExecutor) driver;

// Access the web page
driver.get("http://example.com");

// Accept cookies
driver.findElement(By.id("aceptarCookies")).click();


// Log into account
driver.findElement(By.id("areaPersonal")).click();
driver.findElement(By.id("tab_login_user")).sendKeys(dni);
driver.findElement(By.id("tab_login_password")).sendKeys(passwd);
driver.findElement(By.id("loginFormHeader")).findElement(By.id("buttonHeader")).click();

The bot successfully logs in, but encounters strange behavior when trying to execute further instructions after logging in. For instance, if I attempt to search for an item on the home page right after logging in, it fails because the item has not loaded yet. Adding this instruction below doesn login steps fails:

// Search for body item
driver.findElement(By.id("my_panel_page"));

However, if I add an implicit wait:

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Search for body item
driver.findElement(By.id("my_panel_page"));

Or an explicit wait:

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("id_of_new_item")));
driver.findElement(By.id("my_panel_page"));

The script stalls and does not proceed with any more instructions. If I add a print statement, it never gets executed:

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("id_of_new_item")));
System.out.println("Page loaded!!!");
driver.findElement(By.id("my_panel_page"));

The behavior is puzzling, as Selenium seems to stop functioning once the page finishes loading. It works only when the next page is still loading and the desired HTML objects are not yet available. My current versions are:

  • ChromeDriver: 109.0.5414.74
  • Chrome: 109.0.5414.120
  • Selenium: 3.141.59
  • JDK: 11.0.16.1

I cannot disclose specific details about the webpage due to spam detection measures. However, I have verified that the elements I am searching for in the script exist in the HTML code. This issue only started occurring recently.

EDIT:

Below are examples of output to help identify the problem. When I execute

driver.findElement(By.id("my_panel_page"));
without using any waits, it returns an error message:

... (Initialize ChromeDriver)
    
no such element: Unable to locate element: {"method":"css selector","selector":"#my_panel_page"}
  (Session info: chrome=109.0.5414.120)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'xxx', ip: 'xxx', os.name: 'Windows 11', os.arch: 'amd64', os.version: '10.0', java.version: '11.0.16.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 109.0.5414.120, chrome: {chromedriverVersion: 109.0.5414.74 (e7c5703604da..., userDataDir: C:\Users\xxx\AppData\Loca...}, goog:chromeOptions: {debuggerAddress: localhost:52373}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: 533a8a11a33254b8ab788522dada77ab
*** Element info: {Using=id, value=my_panel_page}

If I use a wait, the ChromeDriver initializes successfully and logs in, but then hangs at the wait statement without printing anything afterward:

Starting ChromeDriver 109.0.5414.74 (e7c5703604daa9cc128ccf5a5d3e993513758913-refs/branch-heads/5414@{#1172}) on port 15136
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
feb. 01, 2023 5:28:28 P. M. org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMACIËN: Detected dialect: W3C

Answer â„–1

Element Presence Verification

presenceOfElementLocated() is a method used to verify the presence of an element in the DOM of a webpage, without necessarily checking if it is visible.


Recommended Approach

Instead of relying solely on presenceOfElementLocated(), it is advisable to employ WebDriverWait for visibilityOfElementLocated(). Here's a suggested implementation:

try 
{
    new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("id_of_new_item")));
    System.out.println("new_item is visible");
    System.out.println("Page loaded!!!");
    driver.findElement(By.id("my_panel_page"));
    // continue with program execution
}
catch(TimeoutException e) {
    System.out.println("new_item is not visible");
}
// remaining lines of the program

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on managing basic authentication (Rest API- Post Request) using selenium webdriver script

What is the best way to implement basic authentication for a Rest-API using Selenium WebDriver and Java? ...

finding elements using Appium is ineffective when it comes to multiple elements

My aim is to retrieve all elements along with their values from a table containing multiple items (IOS). All the items in the table have the same name but different values. I am attempting to fetch all elements at once using: List<WebElement> l = d ...

Checking the effectiveness of Implicit wait in Katalon Studio

public void checkSeleniumTitle() { WebUI.openBrowser('https://www.google.com') driver = DriverFactory.getWebDriver(); driver.manage().window().maximize(); driver.get("https://www.google.com"); // Setting im ...

What is the more effective choice for Automation Testing: Static or Dynamic dropdown menu options?

Currently facing an issue with dropdown selections while conducting automated testing. Selenium's Select(); method has been reliable when running tests in multiple cycles and choosing different options each time. The challenge arises when the dropdow ...

Utilizing Selenium with Python to Extract Link Text Value from Subchild Element in Various Scenarios

I'm currently working with the following code snippet: <div class="_97KWR"> <div class="_12x3s"> <div class="_1PF0y"> <div class="_1xNd0 CTwrR _3ASIK"> <a class="_3bf_k _1WIu4" href="/en/gilgamesh/hola-dola/g ...

What is the best way to set up jest to generate coverage reports for Selenium tests?

I recently made the switch to using jest for testing my JavaScript project after encountering coverage issues with mocha and chai. While my unit tests are providing coverage data, my Selenium tests are not. I've tried various solutions found in outdat ...

Verifying a parameter from a request URL using Selenium - A step-by-step guide

I found myself on the following webpage: http://localhost:8080/login?error=true How do I verify if the error variable contains the value true? https://i.stack.imgur.com/F5TkF.png This is what I have tried so far and failed: https://i.stack.imgur.com/3 ...

Specify various labels and eliminate collections in behat.yml

I am looking to set up multiple tags in my behat.yml file to represent suite names. Within the features folder, there are 4 suites with several .feature files each. For example: admin, themes The tags I want to define are: @admin, @themes. Previously, ...

"Exploring the world of JSON with Android and Java

Just delving into the world of JSON and experimenting with the FLOT graph for displaying graphs via WebView. Struggling with JSON parsing to represent my data as JavaScript expects. Despite hours of tinkering, I can't seem to format my JSON output to ...

What is the best way to choose a particular element on a webpage when there are numerous instances of that element present? Utilizing Selenium Webdriver in Python

My main goal is to target only the "Reply" box highlighted in red, but since there are multiple of these on each page, I need a way to select only the first "Reply" box. How can I specifically choose the initial reply box for every post (using this link as ...

Generate automated php tests by simulating browser behavior, either at the unit or functional level

Is there a way to automatically create unit or functional tests by simulating actions in the browser? I've been thinking about something similar to the iMacros addon for Firefox, where we can record our interactions with elements and it generates a m ...

What is the purpose of using double % in Java or JSP?

Yesterday, while reviewing some code, I came across a line that seemed very peculiar to me. In a JavaScript function, there is a condition checking for a string passed as a parameter in the following manner: "%%unsubscribe%%". See the snippet below for re ...

Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX cal ...

Run code every time a page is accessed

Seeking a method to detect page navigation in selenium using Ruby. While C# and Java have events for this, I cannot locate them in Ruby. Any guidance on where to find this functionality? ...

Writing Xpath for a disabled button in Selenium with Salesforce using Java

I need assistance with creating an XPath that will only work when a button is enabled. If the button is disabled, I do not want the XPath to click on it. Currently, when I write the XPath and check if the web element is enabled, it always returns as enabl ...

Loading a JSON Array into a Spinner Control

I am currently using the following code to populate a spinner, JSONObject jsonResponse = new JSONObject(new String(buffer)); JSONArray myUsers = jsonResponse.getJSONArray("GetBusNamesResult"); ArrayAdapter<String> adapter = new ArrayAdapter<Stri ...

Exploring the world of web automation with Python and Selenium: the age-old debate

Is there a way to identify the CSS selector in the hint table on ? Attempting to locate underlined CSS classes is not yielding results (.mini-suggest__popup.mini-suggest__popup_svg_yes.mini-suggest__popup_theme_flat.mini-suggest__popup_visible) browse ...

Selenium with Python: Unmasking the method to choose an option from a dropdown menu even when the element

I'm currently struggling with completing a form on a specific website. To access the form, you can visit: (please click on "filter inmate list", then use the + button to add a row) def coweta_search(last, first): print("Coweta County Jail") ...

extract data from text node using selenium

Currently, I am working on a web application and testing it with Selenium. Within my code, there is a specific node that I am trying to extract data from. <span>Profile Run <span class="current">23</span> of 29</span> My main obje ...

Troubleshooting sending keys with Selenium WebDriver in Python has been a challenge for me

Attempting to run a simple test: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get('http://google.com') driver.find_element_by_name('q') driver.send_keys('hey&a ...