Reputation: 71
I have a scenario to click on 'X' icon from an overlay. When I check for the element using selenium.isElementPresent("//img[@src='close.jpg']"); it is returning true. But when I perform selenium.click("//img[contains(@src,'close.jpg')]"); action it throws an exception "Element is not currently visible and so may not be interacted with".
Tried with all types of xpath but couldn't resolve the problem.
Upvotes: 0
Views: 4302
Reputation: 7339
first of all try using couple of methods:
public boolean isElementPresent(By selector)
{
return driver.findElements(selector).size()>0;
}
public boolean isElementVisible(By selector){
return driver.findElement(selector).isDisplayed();
}
then if your page not compeltely rendered try using some wait mechanisms:
Thread.sleep(1000);
driver.manage().timeouts().implicitlyWait(2,TimeUnit.SECONDS);
and fluentWait mechanism: .
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(org.openqa.selenium.NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;
fluentWait(By.xpath(..blablabla...)).click();
you can also make jsCode injection: 1) if jQuery is supported
String cssSelector="blablabla";
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\'"+cssSelector+"\');");
stringBuilder.append("x.click();");
js.executeScript(stringBuilder.toString());
2) locating needed element through DOM model: e.g.
String js="document.getElementsByTagName('div')[34].click();"
jsCodeExecution(js);
public void jsCodeExecution(String jsCode){
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(jsCode);
js.executeScript(stringBuilder.toString());
}
try also debug step by step to see exactly where the problem is. Hope it helps you.
Moreover, I recommend you to verify your found css selectors and xpath verify in firepath (addon to firebug in firefox):
Upvotes: 3