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
{
}
Related
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");
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 am looking for a way to check that the page was loaded using Selenium. So basically does the url point to a correct address (in chrome the browser shows something like this) :
I am using the following code:
var driver = new FirefoxDriver();
driver.Url = "SomeUrl";
Currently I am comparing the title to "SomeUrl is not available" and if it matches I mark that the page has failed to load.
But is there a better way?
I would suggest, if you know what control ID/or link or/Class is going to appear on your page. Then wait for that element to appear on screen for a defined period of time.
I that element appears then your next line of code will be executed
Here is the simple version of m method. You can make it more dynamic based on your need.
/// <summary>
/// WaitForElementOnPage() method waits a passed number of seconds for the existence
/// of a passed IWebElement object. If the object is found the method return an IWebElement of the object
/// If the object is not found in the passed number of seconds, the method returns a null IWebElement
/// </summary>
public IWebElement WaitForElementOnPage(string controlID, int waitTime)
{
IWebElement element = null;
IWebElement elementFound = null;
try
{
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(waitTime));
Thread.Sleep(3000);
elementFound = wait.Until<IWebElement>((d) =>
{
element = d.FindElement(By.Id(controlID));
break;
return element;
});
}
catch (Exception ex)
{
Log.Error(ex);
elementFound = null;
}
return elementFound ;
}
I personally try to locate body or frameset element on the page.
Based on my experience while using selenium with chromedriver, page content sometimes doesn't show up and I need to run webdriver.refresh() 1-2 times. It doesn't happen all the time, but I run big amount of chrome instances on one machine and this approach was the most effective for now to avoid this.
So I try to locate body or frameset elements and reload few times before I give up.
The advantage of this solution is also the fact that it will also work in case Chrome changes its messages in the future. It will also work with other browsers.
I am trying test a single page web application with webdriver in page object model using C#. The website javascript intensive and does Lazy loading
i have tried using Explicit wait and used the following code to check if the javascript is active
return jQuery.active == 0
I have tried using a combination of both to know if the page has loaded
WebDriverWait _wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(25));
bool WhenToExit = true;
while (WhenToExit) // Handle timeout somewhere
{
var ajaxIsComplete = (bool)(Browser.Driver as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0");
if (ajaxIsComplete)
{
bool isDisplayed = _wait.Until(d => d.FindElement(By.ClassName("example"))).Displayed;
if(isDisplayed)
{
break;
}
}
Thread.Sleep(100);
int Timer = 0;
Timer++;
if (Timer == 100)
{
WhenToExit = false;
}
}
.But still the webdriver does not wait for the page to load , it just keeps executing the steps ,So i have been forced to use Thread.Sleep(), which i dont want use and its not good practices.
Can some tell me how to Get around this issue,Thank u in advance