This is a simple sign-in script which I am running in Firefox.
What I am trying to do is to print a message if the sign-in is successful or fails.
I gave wrong user/pass to get the error (verified it against the site that it's correct).
The page-title element only displays if user was logged-in successfully. Similarly, the error-msg element only displays if user was not logged-in.
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://www.example.com";
String actualTitle;
// Launch Firefox and direct it to the Base URL
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
// Maximize the browser window
driver.manage().window().maximize();
// Get the actual value of the title
actualTitle = driver.getTitle();
driver.findElement(By.linkText("Signin")).click();
WebElement email = driver.findElement(By.id("email"));
email.click();
email.sendKeys("abc#example.com");
WebElement pass = driver.findElement(By.id("pass"));
pass.click();
pass.sendKeys("abc123456");
driver.findElement(By.id("send2")).click();
// Variables for Dashboard & Error Title
WebElement dashboardTitle = driver.findElement(By.className("page-title"));
WebElement loginFailed = driver.findElement(By.className("error-msg"));
if(loginFailed.getText().contains("Invalid login or password."))
System.out.println("Test passed but login failed.");
else if(dashboardTitle.getText().contains("My Dashboard"))
System.out.println("Logged in successfully.");
else if(dashboardTitle.getText().contains("Account Information"))
System.out.println("Logged in successfully.");
else
System.out.println("You're not logged-in.");
System.out.println("The title of current page is: "+actualTitle);
driver.close();
driver.quit();
User/Pass are not correct so the 'IF' condition should run but in reality it's giving me error that other element (page-title) is not found.
If I remove the other condition (from IF statement) then the script is running without any issue.
I want the script to run and search for both elements and if it finds only one element (which it should be) then it should display it's result instead of giving me the error that other element is not found.
Use the following method to find a web element, this should help you wait and find element, if element not found it will catch the exception and return null or else a WebElement.
public WebElement waitAndGetElement(WebDriver driver, By by, int waitTimeInSeconds) {
try {
return new WebDriverWait(driver, waitTimeInSeconds).until(ExpectedConditions.visibilityOfElementLocated(by));
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
Example:
WebElement loginFailed = waitAndGetElement(driver, By.className("error-msg"), 5);
if(loginFailed != null && loginFailed.getText().contains("Invalid login or password."))
System.out.println("Test passed but login failed.");
Use a try-catch block.
....
....
driver.findElement(By.id("send2")).click();
try {
WebElement dashboardTitle = driver.findElement(By.className("page-title"));
System.out.println("Logged in successfully.");
/* Continue code for correct login credentials
*
*/
} catch(NoSuchElementException e) {
}
try {
WebElement loginFailed = driver.findElement(By.className("error-msg"));
System.out.println("Test passed but login failed.");
/* Continue code for incorrect login credentials
*
*/
} catch(NoSuchElementException e) {
}
System.out.println("The title of current page is: "+actualTitle);
driver.close();
driver.quit();
....
....
Using this code solved my issue:
Boolean exist;
if(exist = driver.findElements(By.className("page-title")).size() == 0){
WebElement errorMessage = driver.findElement(By.className("error-msg"));
if(errorMessage.getText().contains("Invalid login or passwords.")){
System.out.println("Test passed but login failed.");
}
else
System.out.println("error-msg class found but different message in it.");
}
else{
WebElement dashboardTitle = driver.findElement(By.className("page-title"));
if(dashboardTitle.getText().contains("Account Information"))
System.out.println("Logged in successfully.");
else
System.out.println("LOGGED IN");
}
Related
When i try to run my scripts and call this method, when i enter URL into address bar, loading starts and loading take much time,
but sometime when refresh page page proper loaded on the spot so please help me out.
How can i handle this issue in automation.
public static MainPage LaunchBrowserAndLogin(String currentScriptName, String LoginUser) throws Throwable {
try {
killprocess();
LaunchBrowser();
String siteUrl = null;
if (excelSiteURL != null) {
if (excelSiteURL.equalsIgnoreCase("")) {
siteUrl = CONFIG.getProperty("siteName");
}else{
if (excelSiteURL.contains("SiteName")) {
siteUrl=excelSiteURL;
}
}
} else {
siteUrl = CONFIG.getProperty("SiteName");
}
driver.get("https://QA.YYYY.com/ABC9/#/login");
System.out.println("URL for Login: "+siteUrl);
CheckErrorPageNotFound();
driver.manage().timeouts().pageLoadTimeout(Long.parseLong(CONFIG.getProperty("pageLoadTime")), TimeUnit.SECONDS);
enterUserID(currentScriptName, LoginUser);
enterPasswd(currentScriptName);
MandatoryFieldSkipErrMsg("~~~~~~ Mandatory Field is skipped, Getting Error: ");
ClickLoginButton();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
}catch(){
DesireScreenshot("AfterClickOnLoginButton");
String stackTrace = Throwables.getStackTraceAsString(t);
String errorMsg = t.getMessage();
errorMsg = "\n\n\n\n Login failed.See screenshot 'LoginFailed' \n\n\n\n" + errorMsg + stackTrace;
Exception c = new Exception(errorMsg);
ErrorUtil.addVerificationFailure(c);
killprocess();
IsBrowserPresentAlready = false;
throw new Exception(errorMsg);
}
return new MainPage(driver);
}
First you need to check whether page is fully loaded or not in that case we will use the below code.
new WebDriverWait(driver, 5).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Then as per your question I believe that some web elements are not properly getting loaded. So what you can do add one more explicit wait and put that wait inside try catch block as shown below.
try
{
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(By.id("Abhishek")));
System.out.println("Completed");
}
catch( TimeoutException e)
{
System.out.println("Reloading");
driver.navigate().refresh();
}
If it is unable to find that element then in the catch block it will refresh the page and in this way you can proceed further.
Note: I could have written the script for you but application url is invalid.
In my application when user login first time then on first page username is displayed (data driven approach using #factory). But if user logs out and log in again then a new pages comes with following text.
You're signed out now.
Click here to sign in again.
My question is how to check if this text -'Click Here' present then click on it and do same actions as mentioned in login function.
I tried to implement if-else block to check if this webelement is displayed then click on it and do same action as in login function. But it is giving error that
org.openqa.selenium.NoSuchElementException: Cannot locate an element using xpath=//a[#href='/Account/Login']
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Though I'm successfully able to achieve my result by specifying this element to click in Logout function. But when finally my test gets finished it always clicks on it.
#FindBy(xpath="//a[#href='/Account/Login']")
WebElement clickHere;
//function to check
if (clickHere.isDisplayed())
{
clickHere.click();
username.sendKeys(strUsername);
nextBtn.click();
password.sendKeys(strPassword);
loginButton.click();
System.out.println("Successfully Logged");
}
else
{
username.sendKeys(strUsername);
nextBtn.click();
password.sendKeys(strPassword);
loginButton.click();
System.out.println("Successfully Logged");
}
Please suggest a solution to check in login function everytime.
clickHere.isDisplayed() is giving NoSuchElementException as the element is not present on the UI on which you are trying to find it.
So, to solve your problem you can fetch the list of the element through pagefactory and then can find the size of that list, if the size is greater than 0, it means the element is present on the page else the element is not present.
You need to make the following changes in your code and it would work fine then:
You need to fetch the element list using:
#FindAllBy(xpath="//a[#href='/Account/Login']")
List<WebElement> clickHere;
And make the following changes in your code:
if (clickHere.size()>0){
clickHere.get(0).click();
username.sendKeys(strUsername);
nextBtn.click();
password.sendKeys(strPassword);
loginButton.click();
System.out.println("Successfully Logged");
}
else{
username.sendKeys(strUsername);
nextBtn.click();
password.sendKeys(strPassword);
loginButton.click();
System.out.println("Successfully Logged");
}
Replace the (clickHere.isDisplayed()) with below.
if(driver.findElements(By.xpath("//a[#href='/Account/Login']") ).size() != 0)
if you want to stick to your pagefactory then you can use the below approach
// below line will click on the "Click Here" link if only it's present
try {clickHere.click();}catch(Exception e) {}
username.sendKeys(strUsername);
nextBtn.click();
password.sendKeys(strPassword);
loginButton.click();
System.out.println("Successfully Logged");
if you would like to catch only NoSuchElementPresent exception you can update to catch only that.
You can create BaseClass for you PageObject and impelent metchod isElementOnPage
Base class:
public class BasePage {
private WebDriver driver;
public BasePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
protected boolean isElementOnPage(WebElement webElement) {
try {
webElement.getTagName();
} catch (Exception e) {
return false;
}
return true;
}
}
Your Class:
public class PageClass extends BasePage {
#FindBy(xpath="//a[#href='/Account/Login']")
private WebElement clickHere;
public PageClass(WebDriver driver) {
super(driver);
}
public PageClass YourMethod(){
if(isElementOnPage(clickHere)){
clickHere.click();
// your logic here
}else {
// your logic here
}
return this;
}
}
I have my simple selenium program that validate if the value search box in the google is equal to hello world but i got this error:
Exception in thread "main"
org.openqa.selenium.NoSuchElementException: no such element: Unable to
locate element: {"method":"name","selector":"q"}....
Here's my complete code
public class SimpleSelenium {
WebDriver driver = null;
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowserInChrome();
ss.getPage();
ss.listenForHelloWorld();
ss.quitPage();
}
private void openBrowserInChrome(){
System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
driver = new ChromeDriver();
}
private void quitPage() {
driver.quit();
}
private void getPage() {
driver.get("http://www.google.com");
}
private void listenForHelloWorld() {
WebElement searchField = driver.findElement(By.name("q"));
int count = 1;
while (count++ < 20) {
if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Do you wait until the page is ready and element displayed?
I've often got this error when the page is still loading. You could add something like
(MochaJS example, pretty much the same API for JAVA tests)
test.it('should check the field existence', function (done) {
let field_by = By.id(ID_OF_THE_FIELD);
driver.wait(until.elementLocated(field_by,
driver.wait(until.elementIsVisible(driver.findElement(field_by)), TIME_TO_WAIT_MS);
done();
});
You wait until the element is visible. If it failed, the timeout of TIME_TO_WAIT_MS will be raised.
The google search bar will never have "hello world" in it because you haven't typed it in?
Also the search field value doesn't seem to update when you type in a search (if you inspect the element using the Console).
If your just learning I would just write a test like this and the click the search button, then confirm the "hello world" text in the search results:
WebElement searchField = driver.findElement(By.name("q"))
searchField.sendKeys("Hello World")
//Add code to click search button
//Add code to assert results on next page
Also I would completely change your listenForHelloWorld() method and use the built in WebDriver ExpectedConditions:
new WebDriverWait(driver, 10)
.until(ExpectedConditions.textToBePresentInElement(searchField, "Hello World"))
I'm trying to learn selenium webdriver so I started with the basics but my driver.getcurrenturl() does not take the correct url.
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://test.com/");
driver.findElement(By.name("SelectedDomainName")).sendKeys("a");
driver.findElement(By.id("UserName")).sendKeys("b");
driver.findElement(By.id("Password")).sendKeys("#123");
driver.findElement(By.id("loginBtn")).click();
String Url = driver.getCurrentUrl();
if (Url.equals("http://test.com/Home/Index")) {
System.out.println("Login successful");
} else {
System.out.println("Login Failed");
}
}
String url = driver.getCurrentUrl();
This will take the current url, but you need to go to some url first so you need to mention:
driver.get("https://www.test.com/index.html");
After that you can put it in string and validate.
WebDriver driver = new FirefoxDriver();
driver.get("https://www.test.com/index.html");
String url = driver.getCurrentUrl();
if(url.equals("https://www.test.com/index.html")) {
System.out.println("Login successful");
} else {
System.out.println("Incorrect details provided by the User");
}
What URL are you expecting to get? Make sure you navigate to that URL first (see below) and that the navigation has been complete.
driver.get("http://www.google.com");
Before you compare it to other string, print it out and see what's there. Just note that if you are trying to obtain the URL before the navigation has taken place, it will return about:blank string to you.
I'm automating a php web page using webdriver and java language. My code was executing and I was able to perform actions on web page, but today only the login method is executing and my second method gets failed everytime I run. I'm so worried why it is happening. Please help, I'm new in automation testing.
public class TestNGClass {
private String baseUrl = "http://test.com/test2/1.4.6.3/public/admin/";
private WebDriver driver = new FirefoxDriver();
#Test
public void login() {
driver.manage().window().maximize();
driver.get(baseUrl);
driver.findElement(By.name("username")).sendKeys("abc");
driver.findElement(By.name("password")).sendKeys("123");
driver.findElement(By.name("login")).submit();
System.out.print("\nCongrats..You have successfully logged in.");
}
#Test
public void createUser() {
String expectedTitle = "User";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle,"Title Not Found!");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath("//body/div[3]/div[2]/ul/li[2]/a/img")).click();
Error :
java.lang.AssertionError: Title Not Found! expected [User] but found []
This is because you are using Assert.
Assert.assertEquals(actualTitle, expectedTitle,"Title Not Found!");
Make use of Try catch in-order to proceed next step.
try{
Assert.assertEquals(actualTitle, expectedTitle,"Title Not Found!");
}catch (Exception e)
{
}