Selenium stops after click - java

I'm clicking on OK button. Clicks successfully. After that Selenium is not responding. It is not throwing any exception also. When I close the browser window manually then it tries to continue the execution.

I had the same effect, and so I wrote myself a custom Click() method that I call in such cases.
For Internet Explorer, it does a double-click instead of a click, which seems to be necessary sometimes for Selenium to work.
In Firefox, I occasionally got an exception ("Cannot press more then one button or an already pressed button"), so I wrote the following C# code that explicitly releases the button before pressing it (should look similar in Java):
public static void Click(this IWebElement element, TestParams testParams)
{
if (testParams.Target.IsFirefox)
{
var actions = new Actions(driver);
actions.MoveToElement(element);
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.Zero);
actions.Release().Build().TryPerform();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(testParams.DefaultTimeoutInSeconds));
actions.MoveToElement(element);
actions.Click().Build().Perform();
}
else if (testParams.Target.IsInternetExplorer)
{
element.DoubleClick(driver);
}
else
{
element.Click();
}
}
This doesn't always work, so I only call my custom Click() method when really necessary. This produces stable results on the sites I usually test.

Related

How to wait until loading window close or visible false

I have developed selenium automation framework using JAVA and I facing a problem.
When I click on any button say Filter or clear filter application display a loading window and after that, we are able to perform next action.
i have added following code to wait until loading window visible false but its not working.
wait.until(ExpectedConditions.invisibilityOf(webElement));
System.out.println("Wait Untill Loading Window Closed");
existFlag=true;
in web element i passing that loading window XPATH. Every time code not wait for window to be closed start clicking on button and throw exception
unknown error: Element ... is not clickable at point (178, 391). Other element would receive the click:
I also added code for click
wait.until(ExpectedConditions.elementToBeClickable(webElement));
webElement.click();
return true;
Please help how i can wait till loading window close.
You should use implicit wait for this purpose. Add this statement for setting Implicit wait on driver object , after initialising the driver instance.
driver.manage().timeouts().implicitlyWait(Integer.parseInt("30"),TimeUnit.SECONDS);
You can use this :
wait.until(ExpectedConditions.visibilityOfElementLocated(webElement));
webElement.click();
You can write you personal waiter. I guess, you will got a few cases when you will see this scroller. For example you can try use next approach:
public void waitIfScrollerStillVisibe(int seconds, By locator) {
int counter = 0;
while (!isElemenyVisible(locator)) {
if (counter == seconds) {
new throw ElementIsNotVisibleException();
}
else {
Thread.sleep(seconds);
counter++;
}
}
}

moveToElement mouse hovering function in Selenium WebDriver using Java not stable

I'm using Selenium 3.0.1 for running automation tests using TestNG.
In one test I'm trying to hover on an action menu and then click an option in that menu:
Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();
But the test is not stable. I can see the menu opens but immediately closing, so the test fails because it's not finding the option any more.
I'm receiving this error:
java.lang.IllegalArgumentException: Must provide a location for a move action.
at org.openqa.selenium.interactions.MoveMouseAction.<init>(MoveMouseAction.java:30)
at org.openqa.selenium.interactions.Actions.moveToElement(Actions.java:251)
How can I check if the menu is open? the perform() method is returning void.
I notice if I put call the moveToElement twice, than the test is being more stable. Is there any elegant option of doing so?
Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();
builder.moveToElement(actionButton).build().perform();
This how the menu looks like when we hover over it:
I find this issue:
https://sqa.stackexchange.com/questions/3467/issue-with-losing-focus-of-hover-command-when-the-mouse-is-outside-of-the-acti
which explains best my problem. unfortunately, still with no solution.
If it is not necessary for you to open the menu, please try clicking the option using JavascriptExecutor. JavascriptExecutor can click a hidden element as well, all that is necessary for the click to be triggered using JavascriptExecutor is that the element is present on the DOM.
Snippet (Java):
((JavascriptExecutor)driver).executeScript("arguments[0].click()", driver.findElement(By.cssSelector("hiddenOptionFromMenu")));
You can wait for the menu to appear after the hover with a FluentWait, like so:
FluentWait<> wait = new FluentWait<>(getWebDriver())
.withTimeout(driverTimeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(500, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class)
.ignoring(NoSuchElementException.class)
.ignoring(ElementNotVisibleException.class)
wait.until(x -> { return driver.findElement(menuElementBy); } );
If the mouse hover succeeded - the menu starts appearing - there's no reason you need to call it twice.
It seems like a timing issue.
If the menu has a transition effect, then add a delay of the duration of the effect:
new Actions(driver)
.moveToElement(menu)
.pause(100) // duration of the transition effect in ms
.perform();
submenu.click();
You could also wait for the targeted element to become visible and steady (same position returned twice in a row).

Selenium Driver (Chrome) Can't Find Dropdown on hover Element

I'm using the Selenium Chrome Driver to run a couple tests on various site environments, however, when attempting to use an element from a hover drop down menu, I can't seem to reliably select the elements. This works 100% of the time when I'm debugging, but when I run it without an attached debugger it fails about 2/3rds of the time. Here is the code:
private void prepWindow(WebDriver driver, boolean isNightly, String toClick) {
WebDriverWait wait = new WebDriverWait(driver, 300);
try {
if (isNightly) {
WebElement nightlyPopup = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(BOWebElements.nightlyPopup)));
nightlyPopup.click();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Nightly popup has changed names again.", "Error", JOptionPane.ERROR_MESSAGE);
}
WebElement user = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Users")));
Actions action = new Actions(driver);
action.moveToElement(user).build().perform(); //Makes hover drop down appear
driver.findElement(By.id(toClick)).click(); //Should click element that is only visible when hover drop down is open
}
I should also note that the same code above works perfectly without using a debugger on a coworker's computer, but not my own.
I would like to use XPath but unfortunately the elements of the drop down aren't actually children of the link I have to hover over to open the drop down. If I try to navigate directly to the element using the XPath, it gives me an error saying the XPath isn't valid. Here is one of the potential XPaths:
//html/body/#outTemplateId/#preambleFormId/#globalNavigation/#navBGC/#navBGCmainMM/ul/li/ul/table/tbody/tr/td/ul.ui-menu-list.ui-helper-reset/li.ui-menuitem.ui-widget.ui-corner-all/a#fleetUsersId2.ui-menuitem-link.ui-corner-all.submenu
How can I make the behavior consistent?
Chain your actions together to better emulate the actions that a user would take:
action.moveToElement(user).moveToElement(driver.findElement(By.id(toClick))).click().build().perform();
Check out this question for more details:
https://stackoverflow.com/a/17294390/3537915

Wait for a modal to disappear in Selenium 2.0

When my test run using a webdriver for Firefox I'll get modal exception after reaching an accept on an alert:
[Exception]: Modal dialog present
The tests however work fine when using IE webdriver. The problem seems to be that test scenario proceeds before the alert is completely closed. In other words it tried to do the following:
List<WebElement> l = driver.findElements(By.linkText("link"));
and a result I'll get modal exception.
Now wait.until(ExpectedConditions) as mentioned wait.until(ExpectedConditions.visibilityOf Element1 OR Element2) is good candidate. However I am not able to create a condition that returns true when alart disappears. How can I do that?
Edit: to clarify further, the problem is not waiting for the alert to appear (my implicit wait is working fine for that purpose). I do get the alert and apply the test on that however after I click accept on the alert, test goes on fast and tried to proceed with the next step while alert still present and throws the modal present exception. I have also tried the following to prevent that with out success.
driver.switchTo().defaultContent();
There is now default mechanism to wait for alert to appear/disappear but, we can write our own logic something like below instead of waiting for static amount of time (Thread.sleep(10000)).
waitForAlert(WebDriver driver)
{
int i=0;
while(i++<5)
{
try
{
Alert alert = driver.switchTo().alert();
alert.accept();
break;
}
catch(NoAlertPresentException e)
{
Thread.sleep(1000);
continue;
}
}
}
even I faced this problem in FF and I came over this by using a AUI. Try to use the below code to get your alert > accept it and then continue with rest of your code/test.
Actions action = new Actions (driver);
action.click(driver.findElement(By.id("locator"))).build().perform();
driver.switchTo().alert().accept();
// Continue with your test
List<WebElement> l = driver.findElements(By.linkText("link"));

Dropdown click not working in Selenium RC

I am trying to automate test scripts in selenium. Scenario of the activity to be automated:
It should open automatically a page URL first.
Click on the left navigation.
The page then gets populated with a drop-down, it should select a fixed value from the drop down(say = company)
Click a create button at the bottom of the page.
In my case the code is working until the population of drop down but after that the code fails to click the create button as the next action. The error message which I got in the command console is as follows:
Element name = create not found on session c48334c30....96ed
Here is my code:
public class testing {
Selenium selenium = null;
#Test
public void submit() throws Exception {
selenium = new DefaultSelenium("localhost", 4545, "*firefox", "URL");
selenium.start();
selenium.open("URL");
selenium.windowFocus();
selenium.windowMaximize();
selenium.click("link=Work with company names");
selenium.waitForPageToLoad("30000");
selenium.select("//select[#name='company_id']", "label=company");
selenium.waitForPageToLoad("3000");
selenium.click("name = create");
}
}
Please provide me your suggestions to solve this, since I am not able to understand why it is failing to click the button named "create". I also tried to use selenium.click("xpath=//button[matches(#id,'.*create')]"); instead of selenium.click("name = create") but it didnt work as well.
Please let me know what can be the issue for this error and how can I resolve it? Thanks.
1) it would be good if you provide html code of your page.
2) before clicking any element (which is loaded after some action) I recommend using WaitForElementPresent (from Selenium IDE), i.e. be sure that element really exists. Selenium works rather fast and it may try clicking the element before the element actually loaded.
You may use something like this:
public bool waitForElementPresent(string Xpath) {
bool present = false;
for (int second = 0; ; second++) {
if (second >= 5) {
break;
}
if (IsElementPresent(Xpath)) {
present = true;
break;
}
Thread.Sleep(1000);
}
return present;
}
try with this
selenium.click("//*[contains(#name,'create')]");
As you are using: selenium.waitForPageToLoad("3000");
Selenium is waiting for page to load. You want to add a pause, though thread.sleep isn't the best practise it can still work for you.

Categories