Dropdown Element is invisible using Selenium TestNG - selenium

The dropdown element is invisible but it is enable and present.
I have tried everything but I am out of options. Please help. My goal is to click that dropdown that will show a textfield to input a string.
Code snippet:
if(driver.findElements(By.xpath("//*[#id='s2id_autogen3']"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
if( driver.findElement(By.xpath("//*[#id='s2id_autogen3']")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}
if( driver.findElement(By.xpath("//*[#id='s2id_autogen3']")).isEnabled()){
System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}
Output:
Element is Present
Element is InVisible
Element is Enable
enter image description here

You can make Webdriver wait until the visibility of the required drop down and then click on it. Try following and let me know, whether it resolves your issue:
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(
ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='s2id_autogen3']")));
In the above code, Webdriver will wait for a maximum of 60 seconds for the required drop down to become visible. If even after 60 seconds the drop down is not visible, it will fail with a timeout error.

The answer by Mahipal has to work. Other reason might be the Frame. Make sure that dropdown is not inside an Frame.

Related

Cannot click (other element would get click) [duplicate]

I am trying to make some tests using selenium based Katalon Studio. In one of my tests I have to write inside a textarea. The problem is that I get the following error:
...Element MyElement is not clickable at point (x, y)... Other element would receive the click...
In fact my element is place inside some other diva that might hide it but how can I make the click event hit my textarea?
Element ... is not clickable at point (x, y). Other element would receive the click" can be caused for different factors. You can address them by either of the following procedures:
Element not getting clicked due to JavaScript or AJAX calls present
Try to use Actions Class:
WebElement element = driver.findElement(By.id("id1"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
Element not getting clicked as it is not within Viewport
Try to use JavascriptExecutor to bring the element within Viewport:
JavascriptExecutor jse1 = (JavascriptExecutor)driver;
jse1.executeScript("scroll(250, 0)"); // if the element is on top.
jse1.executeScript("scroll(0, 250)"); // if the element is at bottom.
Or
WebElement myelement = driver.findElement(By.id("id1"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
The page is getting refreshed before the element gets clickable.
In this case induce some wait.
Element is present in the DOM but not clickable.
In this case add some ExplicitWait for the element to be clickable.
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("id1")));
Element is present but having temporary Overlay.
In this case induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.
WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
Element is present but having permanent Overlay.
Use JavascriptExecutor to send the click directly on the element.
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
I assume, you've checked already that there is no any other component overlapping here (transparent advertisement-iframes or some other component of the DOM => seen quite often such things in input/textfield elements) and, when manually (slowly) stepping your code, it's working smoothly, then ajax calls might cause this behaviour.
To avoid thread.sleep, try sticking with EventFiringWebDriver and register a handle to it.
(Depending on your application's techstack you may work it for Angular, JQuery or wicket in the handler, thus requiring different implementations)
(Btw: This approach also got me rid of "StaleElementException" stuff lots of times)
see:
org.openqa.selenium.support.events.EventFiringWebDriver
org.openqa.selenium.support.events.WebDriverEventListener
driveme = new ChromeDriver();
driver = new EventFiringWebDriver(driveme);
ActivityCapture handle=new ActivityCapture();
driver.register(handle);
=> ActivityCapture implements WebDriverEventListener
e.g. javascriptExecutor to deal with Ajax calls in a wicket/dojo techstack
#Override
public void beforeClickOn(WebElement arg0, WebDriver event1) {
try {
System.out.println("After click "+arg0.toString());
//System.out.println("Start afterClickOn - timestamp: System.currentTimeMillis(): " + System.currentTimeMillis());
JavascriptExecutor executor = (JavascriptExecutor) event1;
StringBuffer javaScript = new StringBuffer();
javaScript.append("for (var c in Wicket.channelManager.channels) {");
javaScript.append(" if (Wicket.channelManager.channels[c].busy) {");
javaScript.append(" return true;");
javaScript.append(" }");
;
;
;
javaScript.append("}");
javaScript.append("return false;");
//Boolean result = (Boolean) executor.executeScript(javaScript.toString());
WebDriverWait wait = new WebDriverWait(event1, 20);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return !(Boolean) executor.executeScript(javaScript.toString());
}
});
//System.out.println("End afterClickOn - timestamp: System.currentTimeMillis(): " + System.currentTimeMillis());
} catch (Exception ex) {
//ex.printStackTrace();
}
}
As #DebanjanB said, your button (or another element) could be temporarily covered by another element, but you can wait and click it even if you don't know which element is covering the button.
To do this, you can define your own ExpectedCondition with the click action:
public class SuccessfulClick implements ExpectedCondition<Boolean> {
private WebElement element;
public SuccessfulClick(WebElement element) { //WebElement element
this.element = element;
}
#Override
public Boolean apply(WebDriver driver) {
try {
element.click();
return true;
} catch (ElementClickInterceptedException | StaleElementReferenceException | NoSuchElementException e) {
return false;
}
}
}
and then use this:
WebDriverWait wait10 = new WebDriverWait(driver, 10);
wait10.until(elementToBeClickable(btn));
wait10.until(new SuccessfulClick(btn));
Try Thread.Sleep()
Implicit - Thread.Sleep()
So this isn’t actually a feature of Selenium WebDriver, it’s a common feature in most programming languages though.
But none of that matter.
Thread.Sleep() does exactly what you think it does, it’s sleeps the thread. So when your program runs, in the majority of your cases that program will be some automated checks, they are running on a thread.
So when we call Thread.Sleep we are instructing our program to do absolutely nothing for a period of time, just sleep.
It doesn’t matter what our application under test is up to, we don’t care, our checks are having a nap time!
Depressingly though, it’s fairly common to see a few instances of Thread.Sleep() in Selenium WebDriver GUI check frameworks.
What tends to happen is a script will be failing or failing sporadically, and someone runs it locally and realises there is a race, that sometimes WedDriver is losing. It could be that an application sometimes takes longer to load, perhaps when it has more data, so to fix it they tell WebDriver to take a nap, to ensure that the application is loaded before the check continues.
Thread.sleep(5000);
The value provided is in milliseconds, so this code would sleep the check for 5 seconds.
I was having this problem, because I had clicked into a menu option that expanded, changing the size of the scrollable area, and the position of the other items. So I just had my program click back on the next level up of the menu, then forward again, to the level of the menu I was trying to access. It put the menu back to the original positioning so this "click intercepted" error would no longer happen.
The error didn't happen every time I clicked an expandable menu, only when the expandable menu option was already all the way at the bottom of its scrollable area.

Wait for element for certain amount of time

I have been experiencing one issue during test automation implementation. Particularly test checks if a hamburger menu is displayed.
So far I defined the element and subelement, and I need to really wait just one second, and not to waste time If I know that element will not be displayed after several seconds.
WebDriverWait wait = new WebDriverWait(getDriver(), 1);
WebElement hamMenu = el.findElement(By.xpath(HAMBURGER_MENU_GENERAL_XPATH));
How to implement the method findElement in the way it will try to find the element in one sec? I do not wish to stay longer... Thanks
Try this -
WebElement elem = new WebDriverWait(driver, 1).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(HAMBURGER_MENU_GENERAL_XPATH)));
If I summarize your requirement is as follows :
Check if a hamburger menu is displayed only for 1 second : You need WebDriverWait with proper ExpectedConditions
Element may/not not be displayed after several seconds : You need to wrapup your code in a try-catch {} block to be able to proceed further in absence of the hamburger.
Youe effective code can be :
try {
WebElement hamburger = new WebDriverWait(getDriver(), 1).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("HAMBURGER_MENU_GENERAL_XPATH")));
System.out.println("Hamburger is displayed in 1 sec");
//rest of your code
} catch (NoSuchElementException e){
System.out.println("Hamburger wasn't displayed in 1 sec");
//rest of your code
}
I got it. Thanks for all hints. This will wait just only for short time which is intended.
public boolean isHamMenuDisplayed(){
getDriver().manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
if (el.findElements(By.xpath(HAMBURGER_MENU_GENERAL_XPATH)).size() == 0)
return false;
else
return true;}

Unable to locate element when element is still present

Driver is unable to find element on the page even when its present
. Basically Im just trying that when a popup (ad popup which we see in many website) is present it should get clicked. Below is the code :
System.setProperty("webdriver.gecko.driver","C:\\SeleniumDriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("https://www.sportskeeda.com/wwe");
//WebElement popup=driver.findElement(By.className("bullbg"));
WebElement popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]"));
if (popup.isDisplayed())
{
System.out.println("True");
}
else
{
System.out.println("False");
}
ERROR
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Unable to locate element: //div[contains(text(),'Close')]
Please click here to check there is a popup which gets display
Try scrolling to the element first, something might be in the way
WebElement element = driver.findElement(By.id("id"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Use Instead:
Boolean popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]")).isDisplayed();
if (popup == true)
{
System.out.println("True");
}
else
{
System.out.println("False");
}

How to handle external popup using selenium

In my project, there has one advertisement provider who shows us pop up advertisement but Problem is this pop-up will come it's not fixed.Sometimes add not show sometimes comes this pop up after 1 minute and interrupts my test case.
I write a code for close this popup but it's not a perfect solution I think..If anyone can help?
boolean Imclose = wd.findElement(By.xpath(".//*[#class='IM_overlay_close_container IM_overlay_close_button']")).isDisplayed();
if (Imclose == true) {
wd.findElement(By.xpath(".//*[#class='IM_overlay_close_container IM_overlay_close_button']")).click();
}
Try these code, to handle the unwanted pop up page. I have provided 180 seconds of wait. Then Click on close button inside the advertisement pop up page.
After click on advertisement pop up page, another window is getting open, So I have to redirect to my main window, then only further code will execute.
driver.get("https://www.rentbyowner.com/usa");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
try
{
WebDriverWait wait = new WebDriverWait(driver, 180);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//div[contains(#class,'IM_overlay_foreground')]"))));
driver.findElement(By.xpath("//div[contains(#class,'IM_overlay_foreground')]//span[#class='IM_close_text']")).click();
try
{
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles())
{
driver.switchTo().window(winHandle);
//driver.switchTo().window(winHandle).close();
}
driver.switchTo().window(winHandleBefore);
//Verify purpose written code, weather my driver is getting move to parent window or not.
WebDriverWait element = new WebDriverWait(driver, 10);
element.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("top_k_search"))));
driver.findElement(By.id("top_k_search")).clear();
System.out.println("Try block");
}
catch(Exception a)
{
System.out.println("Inner Catch");
}
}
catch(Exception e)
{
System.out.println("Element not present");
//Provide your code here..
}
I observed that this is a normal pop-up overlay over the webpage and not an alert and it appears almost within 60 seconds. So, the below code might just work for you.
//Waiting for the Popup to appear
WebDriverWait wait = new WebDriverWait(driver,60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'IM_overlay_foreground')]")));
//Clicking on the 'Close' text to close the popup.
driver.findElement(By.xpath("//div[contains(#class,'IM_overlay_foreground')]//span[#class='IM_close_text']")).click();
NOTE: You can increase the time from 60 to 90, in case it appears to take longer. Thing is, whenever the popup appears within the timeframe set, it is handled(as in Closed).
Actually it is coming after 30-50 seconds so you have to wait and then click on close button.
System.setProperty("webdriver.chrome.driver", "E:\\software and tools\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.rentbyowner.com/usa");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
WebElement ad=driver.findElement(By.xpath(".//*[#id='IM_target_overlay']/div/div/div/div[1]/a/div"));
WebDriverWait wait= new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(ad));
ad.click();
Refer this link for more information:
Handling Alerts in Selenium Webdriver

Selenium NoAlertPresentException

I'm trying to handle dialog (Ok Cancel type) with selenium WebDriver. So my aim is to click "Ok" button.
Scenario is:
Click button for invoking dialog
button.click();
Try to accept
webDriver.switchTo().alert().accept();
But I'm always getting NoAlertPresentException and seeing that dialog closes almost immediately.
It seems to me that Selenium automatically closes dialog and when I want to accept, there is nothing to accept.
I'm sorry for my bad English.
The usual cause of this issue is that Selenium is too quick and tries to accept an alert that has not yet been opened by the browser. This can be simply fixed by an explicit wait:
button.click();
WebDriverWait wait = new WebDriverWait(driver, 5);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
Step 1:
public boolean isAlertPresent(){
boolean foundAlert = false;
WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
try {
wait.until(ExpectedConditions.alertIsPresent());
foundAlert = true;
System.out.println("isAlertPresent : " +foundAlert);
} catch (TimeoutException eTO) {
foundAlert = false;
System.out.println("isAlertPresent : " +foundAlert);
}
return foundAlert;
}
Step 2:
public boolean tocheck_POP_Dialog()
{ Alert alert;
try
{
alert=driver.switchTo().alert();
}
catch(NoSuchElementException elementException)
{
return false;
}
alert.accept(); //Close Alert popup
return true;
}
Step 3 :
if(dummyPage.isAlertPresent())
{
dummyPage.tocheck_POP_Dialog();
}
public boolean isAlertPresent(){
try{
Alert a = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
if(a!=null){
System.out.println("Alert is present");
driver.switchTo().alert().accept();
return true;
}else{
throw new Throwable();
}
}
catch (Throwable e) {
System.err.println("Alert isn't present!!");
return false;
}
}
Use explicit wait to check the alert and then do the operation. This might help you. :)
Generally it happens because Selenium commands run too quick and it tries to close the alert before it is open. Hence, adding a delay after click event should resolve the issue. Also, if you are using Safari browser for your test, there is some issue with SafariDriver in handling alerts. SafariDriver cannot handle alerts should provide you more details.
Some additional info. for future readers of this thread:
If this exception persists even after the wait aspect is addressed, please check if the following sequence of steps is effective in the test script:
the underlying Html page's DOM is queried/parsed for some purpose (e.g. to look for Form errors)
(before the) driver.switch_to.alert is attempted
When an Alert is shown over an Html page, if the Alert is overlooked and the DOM underlying the Html page is queried first, the Webdriver appears to loose track of the Alert & causes the Exception.
This was observed with: geckodriver 0.21.0, Firefox 66.0b10 (64-bit) ; python 3.6.1 Selenium driver 3.14 (for Python).
Performing (2) before (1) was found to resolve the issue.