Selenium Webdriver ElementNotVisibleException using Java - java

Having reviewed posts on this issue before, but problem persists.
http://preview.harriscountyfws.org/ is a public site, pertaining to this question.
I'm trying to click on a dropdown and select "Channel Status" from the Rainfall dropdown.
I get the following error:
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible: Element is not currently visible and may not be manipulated
I am attaching screenshot with code, but you may also visit the site and press F12 to look at the code.
Here is my current code based on research I have done so far:
Select dropdown = new Select(driver.findElement(By.id("siteType")));
WebElement triggerDropDown = driver.findElement(By.className("k-i-arrow-s"));
triggerDropDown.click();
dropdown.selectByVisibleText("Channel Status");
dropdown.selectByIndex(1);
Neither of the last two code statements shown work (dropdown.select...)
Both result in ElementNotVisibleException.
Well that's not true, because by pressing the triggerDropDown.Click(), the choices are visible!
Click Here For Screenshot

use the below code:
driver.get("http://preview.harriscountyfws.org/");
driver.manage().window().maximize();
Thread.sleep(2000);//use wait using until instead of this wait
WebElement elem = driver.findElement(By.xpath("//span[text() = 'Rainfall']"));
elem.click();
Thread.sleep(2000);
for(int i = 0; i <= 2; i++){//2 is used bacause u have 2 options
Actions actions = new Actions(driver);
actions.sendKeys(Keys.DOWN).build().perform();//press down arrow key
Actions actions2 = new Actions(driver);
actions2.sendKeys(Keys.ENTER).build().perform();//press enter
}
this will click on channel status button.

This is a strange one. I could click on the dropdown easily but clicking on "Channel Status" was not working. There's something about that dropdown that is not acting "normal". I tried the typical WebDriverWait but it doesn't work. Selenium is not waiting for it properly or something else is going on. I rarely recommend Thread.sleep() but in this case I can't figure out a way around it.
The code below works.
String searchText = "Channel Status";
driver.findElement(By.cssSelector("span.k-widget.k-dropdown.k-header")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//li[text()='" + searchText + "']")).click();

Related

Handling right click menu items in selenium java

I want to right click and go the 5th option that is "copy link address".
I have tried the following code and this is the only thing i could i could find on then internet
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.xpath("//*[(#id = \"u_0_1n\")]"));
TimeUnit.SECONDS.sleep(2);
actions.contextClick(elementLocator).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
This code actually scrolls the page downward instead of moving down the right click menu as if the right click menu was never there.
Using context clicks is not something I would recommend as it violates Parallel Testing Best Practices
The tests need to be small, atomic, and autonomous and your current approach assumes that the browser has to be in focus. It means that you will neither be able to do anything while the test is running nor run the tests in parallel.
So instead I would suggest:
Extract href attribute from the link you want to click
Use JavascriptExecutor and Window.open() function in order to open the link in the new tab
Switch to the new tab
Example code:
WebElement link = driver.findElement(By.xpath("//*[(#id = \"u_0_1n\")]"));
String url = link.getAttribute("href");
driver.executeScript("window.open('" + url + "');");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));

java selenium element found but one click does not work

I have a piece of selenium code to look for a certain element and afterwards to click on this same element. The element is found, but after that, the click does not seem to do the trick. Here is the code for finding the element (unfortunately using xpaths, because there are no id's and it uses a lot of selfmade methods):
String taakButton = "Start taak button";
String xpathButton = "//td[contains(text(),'" + datumhelper.formateerDatumVoorFlowAanmaakdatum(SoapHelper.datumVoorAanvraag5SpaarrekeningSns) + "')]/following-sibling::*[4]/button";
WebElement startButton = selenium.searchForElementByXpathWithoutSwitchToFrame(xpathButton, taakButton);
I use the above String xpathButton to store a WebElement in a variable, after that I pass the WebElement to a method in a different class:
The searchForElementByXpathWithoutSwitchToFrame looks for the element and verifies if it is found.
WebElement startTaakButton = selenium.searchForElementByXpathWithoutSwitchToFrame(xpathStartTaakButton, taakButton);
The element is found, now click on it :
selenium.klikStartOfInzienTaak(startTaakButton, xpathStartTaakButton);
The klikStartOfInzienTaak method, which performs the click looks like this:
public void klikStartOfInzienTaak(WebElement webElementToBeClicked, String xpathToBeClicked) throws InterruptedException {
Actions action = new Actions(driver);
//check to see if element is not null
Assert.assertNotNull("WebElement 'startOfInzienTaak' niet gevonden", webElementToBeClicked);
//Thread.sleep(2500);
//I use Action doubleClick in the hope that would work.
action.moveToElement(webElementToBeClicked).doubleClick().build().perform();
I also used regular driver.click(). It seems the element is found because it does not give a NoSuchElementException and I see the focus is on the element to be clicked, but nothing happens:
Button to be clicked
When I uncomment the Thread.sleep it works, but I don't want to be using Thread.sleep.
As you can see in the image below with the loading image, the page seems to be (re)loading again after the element was already found and clicked on. Thats why the Thread.sleep works:
Button found and clicked but page (re)loading
Does anybody know what to do in order for me to remove the thread.sleep? Selenium has to somehow wait again for the page to reload again although the element is already found?
Try JavascriptExecutor to click the element,
Refer code,
WebElement element = driver.findElement(By.xpath(xpathButton));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You can use WebDriverWait function to first find the element in the webpage and then can click on the element. By this i didn't had to use thread.sleep.
WebDriverWait for_element = new WebDriverWait(20, TimeUnit.SECONDS);
for_element.until(ExpectedConditions.elementToBeClickable(driver.findElement(by what means u have to find the path);
dr.findElement().click();
Hope that this works for you as it worked for me!

JAVA/Selenium - clicking the first button on the page works 50% of the time

I'm using Selenium to automate some UI clicking for a web app. One one of the pages I have several buttons leading to some details. They all have the same name, but I'm ok with clicking either one, so I'm just clicking the first one. But... sometimes it works and sometimes it doesn't.
WebElement DetailsButton = setPresentElementByXpath("//input[1][#type='button' and #value='Go to Details']");
DetailsButton.click();
I'm using setPresentElementByXpath to dynamically wait for the element.
private WebElement setPresentElementByXpath(String xpath) throws Exception {
WebElement myDynamicElement = (new WebDriverWait(driver, 15))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
return myDynamicElement;
}
What am I doing wrong?
EDIT: I forgot to mention where it fails. It goes through DetailsButton.click(); without issues, but then it fails on clicking the next thing, the screenshots and logs say that the page that was supposed to be displayed after clicking the button was not there, so I'm assuming the button is not clicked.
Page load speed variation and caching might be the issue. If the element not found exception is happening, use an Explicit Wait for it to be clickable via ExpectedConditions.ElementToBeClickable(By).
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(By.id("myDynamicElement")));
If the exception "another element would receive the click" is happening you can click the element directly with the JavaScriptExecutor. Note: The JS action has no return value (if it worked or not) and does not wait for a page load if one happens after the click, like the Selenium .click() does.
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", element);

Not able to select any element from chosen dropdown having hidden attribute using testNG Selenium 3.3.1 in java

I have tried different ways, but not able to get any success. Please help me to find some solution for this problem.
I am testing an application having a page like this.
Please refer to this page and help me to select values from dropdown given above page.
BTW with the help of following lines, I am able to click on dropdown, but then not able to select any value using different techniques.
WebElement source = driver.findElement(By.cssSelector("#step_language > div.well.well-lg > div > div:nth-child(2) > div > div.mars_chosen_container.clearfix"));
source.click();
Try this way.
driver.get("https://www.marstranslation.com/place-order");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a/span[contains(text(), 'English')]")).click(); //Click on dropdown using xpath locator.
WebDriverWait wait = new WebDriverWait(driver, 15); //Use explicit wait method for find an element
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//ul/li[contains(text(), 'Arabic')]"))));
driver.findElement(By.xpath("//ul/li[contains(text(), 'Arabic')]")).click(); //After explicit wait, click on Arabic option from dropdown using xpath locator.
Try this snippet
WebElement TargetLanguage = driver.findElement(By.cssSelector("#targetLanguageId_chosen>ul>li>input"));
TargetLanguage.click();
Thread.sleep(3000);
// Gets the target languages in the List
List<WebElement> LangElements = driver.findElements(By.cssSelector("#targetLanguageId_chosen>.chosen-drop>ul>li"));
for(WebElement t : LangElements)
{
if(t.getText().equalsIgnoreCase("Arabic"))
{
t.click();
}
}
Here as an example I clicked on Arabic. You can replace the same with your required language and use it.
Hope it works for you. If anything goes wrong please feel free to ask.
I prefer to write functions for things like this since they will likely be reused.
public static void SelectSourceLanguage(String language)
{
driver.findElement(By.cssSelector("a.chosen-single")).click(); // click the dropdown
driver.findElement(By.xpath("//ul[#class='chosen-results']/li[contains(.,'" + language + "')]")).click(); // click the language
}
Then you can call it like
driver.get("https://www.marstranslation.com/place-order");
SelectSourceLanguage("Hindi");

Not able to switch to pop-up window and find any elements in pop-up in Webdriver using Java

I have an application in which i tried clicking on a button and in return it will pop-up a window for filling a new user form. This is not really like a pop-up window, because it has some input fields as well as "save " and "cancel" button. It looks similar to pop-up window in facebook.
Here the code i tried with
Set beforePopup = driver.getWindowHandles();
driver.findElement(By.xpath("/html/body/div/div/div/div[3]/div/div[2]/div[2]/table/tbody/tr/td[3]/table/tbody/tr/td[2]/em/button")).click();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
Set afterPopup = driver.getWindowHandles();
afterPopup.removeAll(beforePopup);
if(afterPopup.size() == 1) {
driver.switchTo().window((String)afterPopup.toArray()[0]);
}
//driver.switchTo().window("Add New User");
//selenium.type("userDetailsBean.firstName","alan1");
//WebElement btnStartQueryInside = driver.findElement(By.xpath("//html/body/div[14]/div/div/div/div/span"));
//btnStartQueryInside.getText();
System.out.println(driver.getTitle());
WebElement firstName = driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/form/div/div/input"));
firstName.sendKeys("alan1");
//driver.switchTo().alert();
//driver.findElement(By.xpath("//html/body/div[14]/div/div/div/div")).getText();
//WebElement firstName=driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/form/div/div/input"));
//firstName.sendKeys("alan1");
/*WebElement lastName=driver.findElement(By.id("userDetailsBean.lastName"));
lastName.sendKeys("harper");
WebElement emailadd=driver.findElement(By.id("userDetailsBean.userEmail"));
emailadd.sendKeys("alan1#derik.com");
WebElement username=driver.findElement(By.id("userDetailsBean.userName"));
username.sendKeys("xalan1");
WebElement password=driver.findElement(By.id("adminPassword"));
password.sendKeys("Derik123");
WebElement repassword=driver.findElement(By.id("adminPassword2"));
repassword.sendKeys("Derik123");
driver.findElement(By.xpath("//html/body/div[2]/div/div/div/div/div[2]/div/div/table/tbody/tr/td/table/tbody/tr/td[2]/em/button")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);*/
Please note that in code I commented some input field filling, because I thought first I will make it working just for 1st field. Please help me how to proceed.
the problem is after clicking the pop-up button, I'm not sure if the control switches to pop-up window or not. the gettitle after pop-up gives the main window title. and it is not able to find the first input field using the xpath or id.
The term window in Selenium means the actual browser window, not frames or just divs. Therefore, your logic is wrong, getWindowHandles() and driver.switchTo().window("Add New User") are not what you are after.
What you need is driver.switchTo().frame().
driver.switchTo().defaultContent(); // optional, use only if driver is already in an iframe
WebElement editUserForm = driver.findElement(By.cssSelector("iframe[src*='editUserForm']"));
// there are other overloads (by frame name, index, id) and locators can be used here.
driver.switchTo().frame(editUserForm);
// make sure your locator here is correct
WebElement lastName = driver.findElement(By.id("userDetailsBean.lastName")); // I doubt this is correct
// from your screenshot, I'd suggest By.cssSelector("[id*='userDetailsBean.lastName'] input")
lastName.sendKeys("harper");
Also just a kindly heads up, your code smells.
Your implicitlyWait wait usage seems wrong, please read the
documentation and the post.
Where did you get selenium.type("userDetailsBean.firstName","alan1");? Did you just copy the line from somewhere else? This looks like Selenium RC to me.
Why driver.switchTo().alert()? Have you read the documentation on what's this for?
Please don't use absolute xpath.
Try use page object if you haven't done that in your real project. (It's fine if you just want to illustrate the problem here)

Categories

Resources