UserQA UserQA - 3 months ago 63
AngularJS Question

Selenium-Unable to locate element using xpath for div class

I am using selenium webdriver in java.I neead to click a menubar. i tried various xpaths and not working.

<div class="menu-toggler sidebar-toggler"> </div>
is the element i am trying to click. I used the xpath
/html/body/div/div[4]/div[2]/div/div[2]/div[2]/div[2]/div/div/div[1]/div[2]/a
.
I am fine with any option that would help me click the menu bar.Stuck here with automation.i use ngwebdriver framework so if it can be done using ngwebdriver is also fine.It would be really great if somebody could help me with this.

<div class="ng-scope" ng-if="loggedIn">
<div class="page-spinner-bar hide" ng-spinner-bar="">
<div class="ng-scope" data-ng-controller="HeaderController">
<div class="page-header md-shadow-z-1-i navbar navbar-fixed-top ng-scope" data-ng-include="'app/main/tpl/header.html'">
<div class="page-header navbar navbar-fixed-top ng-scope">
<div class="page-header-inner">
<div class="page-logo">
<div class="menu-toggler sidebar-toggler"> </div>
</div>
<a class="menu-toggler responsive-toggler" data-target=".navbar-collapse" data-toggle="collapse" href="javascript:;"> </a>
<img class="small-logo" src="assets/img/logo_kart_small.gif">
<div class="top-menu">
</div>
</div>
</div>
</div>

Answer

You should try using By.cssSelector() as below:

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement sideMenuButton = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.menu-toggler.sidebar-toggler")));

Actions actions = new Actions(driver); 
actions.moveToElement(sideMenuButton).click().perform(); 

Edited :- If unfortunately above does not work try using JavascriptExecutor to perform click as below :-

WebElement sideMenuButton = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.menu-toggler.sidebar-toggler")));
((JavascriptExecutor)driver).executeScript("arguments[0].click()",  sideMenuButton);