Arjun
Arjun

Reputation: 361

Selenium webdriver- Unable to click on submenu - amazon.in

I am trying to click on a submneu in amazon.in I could expand the main menu. but can't click on sub menu. I tried two methods. But its showing errors.

Mail category html code:

<li class="nav_pop_li nav_cat nav_divider_before" id="nav_cat_2">Books</li>

Subcategory html

<a href="/Books/b/ref=nav_shopall_books_all?ie=UTF8&amp;node=976389031" class="nav_a nav_item">All Books</a>

I used the following methods

Method 1

driver.get("http://amazon.in");
    driver.manage().window().maximize();
    Actions actions = new Actions(driver);
            WebElement moveonmenu = driver.findElement(By.xpath("//li[@id='nav_cat_2']"));
            actions.moveToElement(moveonmenu).moveToElement(driver.findElement(By.xpath("//a[@class='nav_a nav_item']"))).click().perform();

Method 2

driver.get("http://amazon.in");
        driver.manage().window().maximize();
    //locate the menu to hover over using its xpath
            WebElement menu = driver.findElement(By.xpath("//li[@id='nav_cat_2']"));

            //Initiate mouse action using Actions class
            Actions builder = new Actions(driver);    

            // move the mouse to the earlier identified menu option
            builder.moveToElement(menu).build().perform();

            // wait for max of 5 seconds before proceeding. This allows sub menu appears properly before trying to click on it
            WebDriverWait wait = new WebDriverWait(driver, 5); 
            wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[@class='nav_a nav_item']")));  // until this submenu is found

            //identify menu option from the resulting menu display and click
            WebElement menuOption = driver.findElement(By.xpath("//a[@class='nav_a nav_item']"));
            menuOption.click();

Please tell me why its not working?

Upvotes: 0

Views: 1650

Answers (1)

Subh
Subh

Reputation: 4424

In "Method 1", there was issue with hovering, I guess. Must I say, it was just clicking on the "Main Category" element".

In Method 2", the hovering of "Main Category" is properly happening. The only problem was with the xpath you have chosen to click on the "Sub-Category". The xpath is actually associated with multiple elements. Hence, the code was failing.

Just replace the following codes in your Method 2, it will work:-

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[@class='nav_a nav_item' and .=\"All Books\"]")));

and

WebElement menuOption = driver.findElement(By.xpath("//a[@class='nav_a nav_item' and .=\"All Books\"]"));

Note:- In the above, I have used All Books as the text to be clicked.
( This text must exactly match with what is being displayed in the webpage.)
Similarly, you can replace All Books with other texts such as "Bestsellers, New Releases & Pre-orders, etc."

Upvotes: 1

Related Questions