boopathi boopathi - 3 months ago 47
Java Question

Not able to click Button(element) on Selenium webdriver

enter image description hereNot able to click Button(element) on Selenium webdriver. It's showing no such element exception.

HTML CODE :

<button id="datepicker-354-7412-title" class="btn btn-default btn-sm uib-title" tabindex="-1" ng-disabled="datepickerMode === maxMode" ng-click="toggleMode()" type="button" aria-atomic="true" aria-live="assertive" role="heading">
<strong class="ng-binding">August 2016</strong>
</button>


JAVACODE:

driver.findElement(By.xpath("//*[@id='flip-card']/div[2]/div/div[2]/div[2]/div[1]/div/div[2]/i")).click();
driver.manage().timeouts().implicitlyWait(05, TimeUnit.SECONDS);
//driver.findElement(By.xpath("//ul[@class='uib-datepicker-popup dropdown-menu ng-scope']/li/div/table/thead/tr/th/button[@id='datepicker-758-2620-title']/strong")).click();
//driver.findElement(By.xpath(".//*[@id='datepicker-961-3767-title']")).click();
//WebElement mm=driver.findElement(By.id("datepicker-1164-5186-title"));
//mm.click();
/*WebElement element=driver.findElement(By.xpath("//*[@id='datepicker-354-7412-title']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click()", element); */
driver.findElement(By.xpath("//button[@id='datepicker-354-7412-title']/strong")).click();

Guy Guy
Answer

The id might be dynamic, try to locate the button by partial id that contains datepicker and title

driver.findElement(By.cssSelector("[id*='datepicker'][id*='title']")).click();

You can also use explicit wait to make sure the button exist/visible before clicking on it

WebDriverWait wait = new WebDriverWait(driver, 10);

// visible
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[id*='datepicker'][id*='title']")));
button.click();

// or exist
WebElement button = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("[id*='datepicker'][id*='title']")));
button.click();