Search code examples
javaselenium-webdriverxpathselenium-chromedriverwebdriverwait

Inconsistent Click and Menu Access Using Selenium


I use the following code to open a menu and then click on an item on the menu. It works fine the majority of the time but occasionally it throws the following error. Is there a better way to interact with this menu and not receive an error inconsistantly:

Exception in thread "main" org.openqa.selenium.ElementNotInteractableException: element not interactable: has no size and location (Session info: chrome=108.0.5359.125)

My code is below.

            // Move to and click Manage Users button / dropdown 
            Actions actions4 = new Actions(driver);
            actions4.moveToElement(driver.findElement(By.xpath(
                    "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/button")))
            .click().perform();
            
            // Move to and click on View User
            actions4.moveToElement(driver.findElement(By.xpath(
                    "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/ul/li[1]/a")))
            .click().perform();

The menu I am interacting with is below.

enter image description here

Source code for the initial button being interacted with:

<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><span class="glyphicon glyphicon-user"></span> Manage User&nbsp;<span class="caret"></span></button>

Solution

  • Instead of locating the element with driver.findElement try changing it to wait.until(ExpectedConditions.elementToBeClickable(locator)) so that your code will be as following:

    WebDriverWait wait = new WebDriverWait(webDriver, 30);
    // Move to and click Manage Users button / dropdown 
    Actions actions4 = new Actions(driver);
    actions4.moveToElement(wait.until(ExpectedConditions.elementToBeClickable(By.xpath(
                        "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/button")))).click().perform();
                
    // Move to and click on View User
    actions4.moveToElement(wait.until(ExpectedConditions.elementToBeClickable(By.xpath(
                        "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/ul/li[1]/a")))).click().perform();
    

    Also I would recomend you to improve your locators. They are too long and breakable.
    Also maybe you do not need to perform click with Actions, it can be done with regular Selenium click since lements are clickable? However I'm not sure about this. It depends on the actual page you working on.