Search code examples
javaseleniumxpathcss-selectorswebdriverwait

How do I get Id, className, or CSS Selector from dropdownmenu that is div for selenium in java


I tried every tag to get this element but it not working any help on this.

WebElement filterSizeDropdown = driver.findElement(By.cssSelector("#maincontent > div > div > div.klevuLanding.klevuTarget.kuLEFTFilters.kuSearchResultsPageContainer.kuCategoryPageContainer > div > div > div > div.kuResultsListing > div > div > div > div > section:nth-child(2) > div:nth-child(1) > div.kuDropdown.kuDropItemsPerpage > div.kuDropdownOptions > div:nth-child(2)"));
filterSizeDropdown.click();

Here is my code.

The problem is that the dropdown menu is not wrapped in select options. I dont know how to get this item element. Can anyone give me some hints?

https://store.liverpoolfc.com/living?productListFilters=&productListPgNo=1 Here is the web page that I am testing (it is for university project), I need to get element of Size dropdown and click on some value :) Any help would appreciate


Solution

  • On that page you need to hover over the drop-down div element to make the drop-down options presented. Then you are able to get the locators of presented options. Here I selected 9-10 size. Of cause before doing all this we need to close the cookies banner. The following code works:

    driver.get("https://store.liverpoolfc.com/living?productListFilters=&productListPgNo=1");
    WebdriverUtils.clickVisible(driver,By.id("onetrust-accept-btn-handler"));
    WebElement dropDown = WebdriverUtils.waitForVisibilityOfElement(driver,By.xpath("//div[@class='kuFilterHead kuCollapse'][contains(.,'Size')]"));
    Actions action = new Actions(driver);
    action.moveToElement(dropDown).build().perform();
    WebdriverUtils.clickVisible(driver,By.cssSelector("[data-optioncount='10'] [title='9-10'] .kuFilterIcon"));
    

    The methods I used here are implemented as following:

    public static boolean clickVisible(WebDriver driver, By locator, int timeout) {
        try {
            Wait<WebDriver> wait = new WebDriverWait(driver, timeout);
            wait.until(ExpectedConditions.visibilityOfElementLocated(locator)).click();
            return true;
        } catch (Exception e) {
            ConsoleLogger.error("Failed to click on element" + e.getMessage());
            return false;
        }
    }
    
    public static WebElement waitForVisibilityOfElement(WebDriver driver, By locator, int timeout) {
        try {
            Wait<WebDriver> wait = new WebDriverWait(driver, timeout);
            return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
        } catch (Exception e) {
            ConsoleLogger.error("Failed to find the element visible" + e.getMessage());
            return null;
        }
    }
    

    The result is:

    enter image description here