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.
Related
I am trying to test if the URL of the window is correct after clicking on a link. But unexpected windows with URL data:, get open between the test and getCurrentUrl grabs the "data:," as the URL and fails the test instead of the actual URL.
The windows with data:, is open even after all the test is complete.
Feature steps:
public void homePageOpens() {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains("STORE"));
String homepageUrl = navigationUser.getUrl();
System.out.println(homepageUrl);
Assert.assertTrue(homepageUrl.contains("https://www.example.com/index.html"));
driver.close();
}
Navigation steps:
#Step("Get the URL")
public String getUrl() { return basePage.getUrl();
}
BasePage:
public String getUrl() {
System.out.println("just testing");
WebDriver driver = new ChromeDriver();
return driver.getCurrentUrl();
}
Replacing base page code with the following worked:
WebDriver driver = new ChromeDriver();
return driver.getCurrentUrl();
to
return getDriver().getCurrentUrl();
public class WorkingWithChrome {
ChromeDriver driver;
String url = "http://qatechhub.com";
String urlface = "https://www.facebook.com/";
public void invokeBrowser() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\fabio\\eclipse-workspace\\libs\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
}
public void invokeBrowser2() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\fabio\\eclipse-workspace\\libs\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
driver.navigate().to(urlface);
driver.navigate().to(url);
driver.getCurrentUrl();
}
public static void main(String[] args) throws Exception {
WorkingWithChrome wc = new WorkingWithChrome();
wc.invokeBrowser();
wc.invokeBrowser2();
}
driver.quit();
}
}
Everythink is working, but the "getCurrentUrl()" when it get's to that aprt the code just stop's, the page dosnt even close.
I'v also tried to use String currentUrl = driver.getCurrentUrl(); but it didnt worked, does somebody know's how do I do it ?
(Im new in Selenium and in programming overall)
First you should add a delay between driver.navigate().to(url); and driver.getCurrentUrl(); to let the page loaded.
Now driver.getCurrentUrl(); returns a value as a String so you can print it as mentioned with System.out.println("Current URL : " + driver.getCurrentUrl());
And after that add driver.quit(); to quit
As #prophet has mentioned, your driver.quit(); is misplaced.
Also, driver.getCurrentUrl(); returns the string. So unless you accept that value in some variable and print it out, you won't know what it's doing.
So please do something like following :
public void invokeBrowser2() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\fabio\\eclipse-workspace\\libs\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
driver.navigate().to(urlface);
driver.navigate().to(url);
System.out.println("Current URL : " + driver.getCurrentUrl());
driver.quit();
}
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.
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");
}
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)
{
}