Selenium finds it challenging to interact with an element when using a headless browser, although the code performs well with a user interface browser

I am encountering a problem with clicking on a submenu option in a dropdown menu on my webpage. The dropdown menu is created using 'span' and 'li' elements, and it contains options that have submenus visible when you click on the parent menu. When I use the UI browser (chrome or firefox), this code works fine:

webDriver.findElement(By.xpath("//span[contains(text(), '" + menuOption + "')]"));

However, when I try to run the same code in headless mode for the same browser, I receive an error:

org.openqa.selenium.ElementNotInteractableException: element not interactable

I have experimented with different strategies such as selecting the parent before clicking on the child node, but the results are consistent:

webDriver.findElement(By.xpath("//span[contains(text(), '" + sItemActionMenu + "')]")).isSelected();
webDriver.findElement(By.xpath("//span[contains(text(), '" + menuOption + "')]"));

I have explored various solutions including using JavascriptExecutor, waiting for the element to be visible, etc:

Unable to Click Button with Headless Selenium Browser

Click on hidden element Selenium webdriver(javascript)

Selenium - cannot click on hidden element

Selenium - Unable to click on link from dropdown list

Unfortunately, none of these solutions provide a clear answer or resolve my issue even after attempting the JavascriptExecutor method:

    JavascriptExecutor js = (JavascriptExecutor) DriverFactory.getDriver();
    WebElement weItemMenu = webDriver.findElement(By.xpath("//span[contains(text(), '" + menuOption + "')]"));

The specific section of code I am trying to access is:

<div class="menu-panel-wrapper" style="top: 0px; left: 1384.83px;"> 
...
...
...
        </li>
    </ul>
</div>

For confidentiality reasons, I cannot share the exact menu structure, but the referenced code snippet accurately reflects its layout.

I have also attempted the following approach:

webDriver.findElement(By.xpath("//ul[@id=\"$pNavi1614647592355$pElements$5\"]//li//span[contains(text(), '" + menuOption + "')]")).click();

However, this does not work for either the UI browser or the headless one. In all the scenarios described above, 'menuOption' represents a variable passed to determine the specific submenu option to click on (e.g., MenuItem1, Menu Item 2, Menu Item3, etc.)

If anyone has suggestions on how to successfully click on a submenu option in the provided code structure, please advise. These submenu options appear to be initially hidden and only become visible once their parent option is selected in the UI.

Answer №1

It seems that the sequence of actions you are performing involves moving to the first element and then clicking on the second one. To ensure smooth execution, consider waiting for the first element to become clickable and utilize the Actions class in this manner:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Click {
    private final WebDriver driver;
    private By parentMenu = By.xpath("//span[contains(text(), 'Parent MenuItem')]");
    private By subMenu = By.xpath("//span[contains(text(), 'MenuItem5')]");

    public Click(WebDriver driver) {
        this.driver = driver;
    }

    public Click clickSubMenu() {
        WebDriverWait wait = new WebDriverWait(driver, 15);
        wait.until(ExpectedConditions.elementToBeClickable(parentMenu));
        Actions action = new Actions(driver);
        action.moveToElement(driver.findElement(parentMenu)).moveToElement(driver.findElement(subMenu)).click().build().perform();
        return this;
    }
}

If elementToBeClickable doesn't yield desired results, consider using visibilityOfElementLocated as an alternative approach.

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

Troubleshooting AngularJS: Resolving Issues with ng-model

Our website is experiencing issues with AngularJS functionality. Here's an example of the code we tested: register.html: <form name="register_form"> <ion-view view-title="Login" align-title="center"> <ion-content style="ba ...

Exploring The Depths of HOC with Enzyme and TypeScript

I have a higher-order component (HOC) that I need to test. During shallow mounting, I need to call some class methods: it('Should not call dispatch', () => { const dispatch = jest.fn() const WrappedComponent = someHoc(DummyComp ...

Displaying the outcome of an HTML form submission on the current page

Within the navigation bar, I have included the following form code: <form id="form"> <p> <label for="textarea"></label> <textarea name="textarea" id="textarea" cols="100" rows="5"> ...

transfer a javascript variable with ajax

I am currently developing a website that contains multiple forms, most of which will be submitted using jQuery AJAX. Although I have implemented reCAPTCHA for security reasons, the client is not satisfied with it due to the difficulty in reading the words ...

I am having trouble loading materials from JSONLoader in Three.js

Hi there, I am working on implementing a simple TheeJS code that will allow me to load some 3D js files using JSONLoader. These 3D files were exported from Blender exporter, but when I run this part of the code, I encounter two errors: Uncaught TypeError: ...

"What is the best way to retrieve the value of a div element with jquery

Attempting to retrieve the value of a div using jQuery in Chrome console from this HTML: <div class="col-md-3"> <div class="vou-col" style="cursor: pointer"> <h4>Free Large Bucket</h4> <span class="sku-info">Voucher ...

Encountering an unknown provider error in AngularJS while using angular-animate

Upon removing bower_components and performing a cache clean, I proceeded to reinstall dependencies using bower install. However, the application failed to load with the following error message: Uncaught Error: [$injector:unpr] Unknown provider: $$forceRefl ...

Place the input field and submit button side by side horizontally

How can I align my submit button next to the input text in a single row, with the submit button on the right side of the input text? This is my code: <div class="mt-12"> <input id="grid-text" ...

Implementing Ajax calls and retrieving JSON arrays within Laravel 5

I'm just diving into the world of "AJAX" and have been experimenting with sending a request "ONSELECT" using "AJAX" in order to receive a "JSON" response in "laravel 5". Below is my View setup: <select> <option data-id="a" value="a">a< ...

Avoid the presence of HTML tags in the content before using the Google Translate API for

I have recently learned about the <span class="e;notranslate"e;> </span> tag that is used to prevent text from being translated within the span element. My goal now is to send content with HTML tags to the Translate API and have it return with ...

The startup process encountered an error while initializing addons.manager

I encountered the following error message. Can it be ignored as a warning or is it a critical error? Any assistance is appreciated. My test code is running properly, except for opening an additional blank browser window. I am currently using selenium 3.4. ...

The end of the /if in the small template system fails to correctly detect the desired condition

If I write the following line on its own, he cuts it without any reason. So...: Greetings, I'm in need of assistance regarding an issue that is currently beyond my understanding. I'm facing a challenge with a small TPL-System which requires so ...

Refresh webpage with updated title

I have hyperlinks to other sections within the same HTML document. When users click on these links, they open in a new tab. However, I want each new tab to have its own unique title. How can I achieve this without changing the title of the current tab? T ...

Toggle visibility of button based on current selection

I am currently working on a script that allows users to select and press "Next" to reveal another set of steps. In order to proceed to the next step, I want to have the submit button disabled by default and only enabled if the user has made at least 2 sele ...

Display numerous divisions depending on the choices made in several Select2 fields

I need assistance in creating a website without using check-boxes, and I believe jQuery Select2 is the solution. However, I am facing an issue where I cannot display multiple divs based on multiple Select2 selections. For instance, if "OnBase" is selected ...

SweetAlert will only render if it is not hidden

One of the components in my codebase utilizes SweetAlert from "react-bootstrap-sweetalert". The issue I am facing is that even when the "show" property is set to false, SweetAlert is still being rendered and the function inside it gets called regardless o ...

MD-List Equilibrium Elevation

Seeking a solution for implementing a simple chat using the md-list template. The issue arises when new items are added to the md-list, causing it to expand. Desiring the list to behave similarly to other chat platforms, where the height remains constant ...

Retrieve the toggle input value to change the page view using jQuery

I'm currently working on a web photo gallery project and I am looking to incorporate a toggle input button that allows users to switch between displaying albums or all photos. To achieve this, I need to extract the value of the input using jQuery and ...

What is the proper way to retrieve the Nuxt context within the fetch() hook?

Is there a way to access the props within an async fetch() function when also using async fetch(context)? I'm trying to figure out how to work with both simultaneously. ...

How to defer the rendering of the router-outlet in Angular 2

I am currently working on an Angular 2 application that consists of various components relying on data fetched from the server using the http-service. This data includes user information and roles. Most of my route components encounter errors within their ...