chris stewart
chris stewart

Reputation: 27

Trying to hover mouse over tabs and perform automated click on a particular item in Selenium

I am trying to perform a mouse hover over a Men category tab and select "Shirts" category on this website. However I am not able to click the "shirts" category in Men item also I m not getting any error too. Here is my code:

public void PurchaseItemTest() throws InterruptedException, IOException {
        Thread.sleep(3000);

        //util.clickbyXpath(Constants.MENCATEGORYTAB);

         WebElement element = util.getdriver().findElement(By.xpath("//a[@class='accord-header' ]"));

            Actions action = new Actions(util.getdriver());

            action.moveToElement(element).moveToElement(util.getdriver().findElement(By.xpath("//a[@class='accord-header' and contains(.,'Men')]"))).moveToElement(util.getdriver().findElement(By.xpath("//a[@title='Shirts']"))).click().build().perform();

Upvotes: 0

Views: 309

Answers (1)

Parabolord
Parabolord

Reputation: 312

This works:

final By DROPDOWN = By.cssSelector("li[class='atg_store_dropDownParent']");
final By DROPDOWN_LINK = By.cssSelector("a[class='accord-header ']");

List<WebElement> dropdowns = new WebDriverWait(util.getDriver(), 5)
        .until(ExpectedConditions.presenceOfAllElementsLocatedBy(DROPDOWN));

WebElement men = dropdowns.stream()
    .flatMap(dropdown -> dropdown.findElements(DROPDOWN_LINK).stream())
    .filter(link -> link.getText().equals("MEN"))
    .findFirst()
    .orElse(null);

if(men != null) {
    new WebDriverWait(util.getDriver(), 5)
        .until(ExpectedConditions.elementToBeClickable(men));
    Actions action = new Actions(util.getDriver());
    action.moveToElement(men).build().perform();
    new WebDriverWait(util.getDriver(), 5)
        .until(ExpectedConditions.elementToBeClickable(SHIRTS))
        .click();
}

Your xpath for the Men category tab was acting wonky for me. When you hover, make sure to wait for the "Shirts" link to be clickable before clicking. Also, avoid using Thread#sleep() with Selenium. Use Explicit Waits instead.

Upvotes: 1

Related Questions