I am new to Selenium, and I am trying to verify that if user has successfully landed on the Home page or not. Here is the snippet:
LoginPage.GoTo();//Goes Well
LoginPage.LoginAs("UserName").WithPassword("Password").Login();//goes Well
Assert.IsTrue(HomePage.IsAt, "Failed to login");//Below is the implementation of HomePAge.IsAt
public static bool IsAt
{
get
{
var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(5));
wait.Until(x => x.SwitchTo().ActiveElement().GetAttribute("id") == "IDHere");//Here the exception is occuring.
}
var homePage = Driver().Instance.FindElement(By.Id("IDHere"));
// return true or False;
Can someone please help?
When an alert is present on your browser, it prevents you from actually doing ANYTHING else.
FYI, when I try to run my application, a window authentication pop up
comes and after that Page loads.
Well, yeah. That's the alert part from "Unhandled Alert Exception". The unhandled part, is because you didn't use any line of code to show your program how to handle the alert. Selenium goes to login page. Then tries to run this line x.SwitchTo().ActiveElement().GetAttribute("id") == "IDHere", but there is an alert on your page that prevents you from doing anything.
You have to actually try to handle it (close it or accept the message) and THEN do anything else.
It might be considered a good practice to wait for your alert to appear (since it might not appear instantly), and then, after (e.g.) 5 seconds, if there is no alert, run your code.
Try the code below to see if it resolves your problem:
public static boid WaitForAlert(bool accept)
{
//Initialize your wait.
WebDriverWait wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(5));
//Wait for alert
try
{
wait.Until(ExpectedConditions.AlertIsPresent());
if (accept)
{
Driver().Instance.SwitchTo().Alert().Accept();
}
else
{
Driver().Instance.SwitchTo().Alert().Dismiss();
}
}
catch (WebDriverTimeoutException) { /*Alert did not appear, do nothing*/ }
}
And then do:
LoginPage.GoTo();
LoginPage.LoginAs("UserName").WithPassword("Password").Login();
LoginPage.WaitForAlert(true); //True to accept the alert
Assert.IsTrue(HomePage.IsAt, "Failed to login");
Related
I'm writing a bot with c # selenium. (The working logic of the bot is simply that there are 20 companies on each page, they go back to the detail page and get the data back. They go through all the companies in order. After getting the data of the last company, they continue to the next page.) After visiting 200-250 companies, the page in the picture opens. Bot's stopping progress. If I press the F5 menu manually, the bot continues to progress, but it doesn't work when we try with the code.
How do I resolve this error?
Error Page
I noticed it was on the way back from the detail page of this page. To go back;
driver.navigate().Back();
driver.navigate().GoToUrl("");
//I tried to go back with the codes but the solution was not.
I get this Error because the error page does not pass.
Bot needs to visit all companies without encountering an error page.
A correct approach for this is to wait for some amount of time for some element you expect on the page using WebDriverWait.
In this example, I wait for 10 seconds and look for element id 'some-id'.
You can change the criteria by replacing By.Id("some-id") with some other condition.
More about By class.
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("https://www.somedomain.com");
var validPage = false;
try
{
validPage = wait.Until(c =>
{
try
{
return driver.FindElement(By.Id("some-id")) != null;
}
catch
{
return false;
}
});
}
catch
{
// not exist
}
if (validPage == true)
{
// ok.
}
else
{
}
I am automating some tests for a webapp written in ASP.NET MVC5 that also uses jQuery. I've been looking around for options on handling an alert confirmation box while using Selenium in IE.
I need to confirm the message on the box, but I do not need to click anything on the dialog. Here is what I have now:
public bool IsAlertPresentAndCorrect(string Message)
{
try
{
WebDriverWait Wait = new WebDriverWait(Driver, System.TimeSpan.FromSeconds(10));
Wait.Until(ExpectedConditions.AlertIsPresent());
ReadOnlyCollection<string> Handles = Driver.WindowHandles;
string ToUse = "";
foreach (string Handle in Handles)
{
if (!Driver.CurrentWindowHandle.Equals(Handle))
{
ToUse = Handle;
}
}
IAlert Alert = (IAlert) Driver.SwitchTo().Window(ToUse);
return Alert.Text.Equals(Message);
}
catch (NoAlertPresentException)
{
return false;
}
finally
{
_driver.SwitchTo().DefaultContent();
}
}
I have also tried IAlert Alert = Driver.SwitchTo().Alert() and IAlert Alert = Driver.SwitchTo().ActiveElement() in place of getting the window handle but they are not working either.
The problem has been the exact same no matter what code I use: OpenQA.Selenium.UnhandledAlertException: Modal dialog present.
Any help would be greatly appreciated
Alert in Chrome:
Alert in IE:
In case of alert you don't necessarily have to switch back to the window handle. You can simply switch to alert, perform necessary operation, close the alert.
I modified your code a bit to fetch the alert text in a variable, close the alert pop-up then compare the alert text with the message passed in parameter and return bool value.
public bool IsAlertPresentAndCorrect(string Message)
{
try
{
WebDriverWait Wait = new WebDriverWait(Driver, System.TimeSpan.FromSeconds(10));
Wait.Until(ExpectedConditions.AlertIsPresent());
string alertText = Driver.SwitchTo().Alert().Text;
Driver.SwitchTo().Alert().Accept();
return alertText.Equals(Message);
}
catch (NoAlertPresentException)
{
return false;
}
}
We are using Selenium with C#. We have a driver script where we instantiate the driver and then we call a testscript (automated functional testcase flow). Everything works well when the object is present on the page. We are facing issue of driver getting killed when we try and verify that certain object is not present, below is the code
Driver Script Code
//driver = new RemoteWebDriver(new Uri(uri), capabilites,TimeSpan.FromSeconds(120));
Test Script Code
public class GraphNew
{
public Boolean testGraphNew(IWebDriver driver, Logger OneLogger)
{
try
{ //Navigate to a page
try
{
driver.FindElement(By.XPath("//a[contains(text(),'Add New Claim')]")).Click();
}
catch
{
OneLogger.Log("Element is not prsent")
}
}
}
catch(Exception e)
{
OneLogger.LogException(e);
return false;
}
}
The problem is when the object is not identified (as it is not present) in the inner try, rather than going to the inner catch block, the execution proceeds to outer catch and shows exception as -
{"The HTTP request to the remote WebDriver server for URL
http://localhost:4449/wd/hub/session/35c483a6-6871-425a-a936-aeebb0742fd2/element
timed out after 120 seconds."}
and driver gets killed.
Can anyone please suggest, if we are missing something or what should be the idle way to code so that once the object is not identified, driver does not get killed and execution continues for the remaining code.
You can do something like below ...
The code is in java but it is very similar/near to C#
You can check first whether your element is present or not in your HTML DOM to prevent from error/failer of script. like below:-
(I am replacing size to lenght in below code as lenght is using in C# to determine the size of array)
if (driver.findElements("YOUR LOCATOR").Length() != 0) {
driver.findElement(YOUR LOCATOR).click();
System.out.println("element exists");
}
else{
System.out.println("element is not exists");
}
You can also use isDisplayed() method of selenium, it will return boolean value. true if element exist on DOM.
Boolean result = driver.findElement(By.xpath("//a[contains(text(),'Add New Claim')]")).isDisplayed();
if(result==true)
{
System.out.println("element exists");
}else{
System.out.println("element is not exists");
}
Refer below link if you want to know more about isDisplayed() method
http://www.softwaretestinghelp.com/webdriver-commands-selenium-tutorial-14/
Hope it will help you :)
I wrote code in C# use Selenium which tests functional. The goal is to put some text in a field, press a button and wait until the site after few times show additional forms. But my code works very strangely. If time very short: it works perfectly. But if the time is more than 30 sec, it throws exception. Here is part of my code, which wait when page loaded by Ajax data and show in the page:
while (true)
{
try
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
IWebElement myDynamicElement = driver.FindElement(By.Id("smapxml"));
Console.WriteLine("Done");
if (myDynamicElement != null)
{
Console.WriteLine("Ok. Element not null. Follow next step.");
break;
}
}
catch (Exception error)
{
Console.WriteLine("error."+error.ToString());
return;
}
}
Exception:
OpenQA.Selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"smapxml"}
in OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:line 1092
So how do I fix this?
I have written an nUnit test using selenium in c#.
All was going well until I have to confirm a JS confirm box.
here is the code I am using:
this.driver.FindElement(By.Id("submitButton")).Click();
this.driver.SwitchTo().Alert().Accept();
The confirm box appears after the submit button. The confirm appears and then disappears immediately but the form does not submit. The behaviour is the same regardless of the accept() line above.
I am using Firefox v15.0.1 and selenium v2.24
I have tried putting a Thread.Sleep between the submit click and the confirm accept.
Everything I have read has said that the selenium driver will automatically send a confirm OK, but something else seems to be happening.
in this issue i would try to verify confirm box presence.
it be something like:
this.driver.FindElement(By.Id("submitButton")).Click();
boolean presentFlag = false;
try {
// Check the presence of alert
Alert alert = driver.switchTo().alert();
// Alert present; set the flag
presentFlag = true;
// if present consume the alert
alert.accept();
} catch (NoAlertPresentException ex) {
// Alert not present
ex.printStackTrace();
}
return presentFlag;
}
then if doen't work. try to debug step by step.
some additional info concerning alert ( confirm boxes) handle in selenium here
hope this somehow helps you
You just need:
IAlert alert = driver.SwitchTo().Alert();
alert.Accept();
The end point I am testing does not have reliable response times and the only way I could get it to always work with webdriver selenium-dotnet-2.33.0 (.NET4) using Firefox was by doing the following:
private void acceptAlert(){
string alertText = "";
IAlert alert = null;
while (alertText.Equals("")){
if (alert == null)
{
try{
alert = driver.SwitchTo().Alert();
}
catch{
System.Threading.Thread.Sleep(50); }
}
else{
try{
alert.Accept();
alertText = alert.Text;
}
catch (Exception ex){
if (ex.Message.Equals("No alert is present")) alertText = "Already Accepted";
else System.Threading.Thread.Sleep(50);
}
}
}
}