driver.getCurrentUrl() returns data:, instead of actual URL - selenium

I'm writing a test with Serenity BDD-Cucumber.
I want to check if the URL is correct when it's navigated. But the result always shows data, and my test fails with driver.getCurrentUrl().
Please see my code below:
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();
}
This also opens a page with URL: "data:," which doesn't close after the test

Use driver.get in order to navigate somewhere.
String someUrl = "https://www.example.com/index.html";
driver.get(someUrl);
This code:
public String getUrl() {
System.out.println("just testing");
WebDriver driver = new ChromeDriver();
return driver.getCurrentUrl();
}
just launch the browser, and the initial url is data:,.
Also it's unclear why BasePage getUrl() method launches the new webdriver and uses it as a local variable. But in homePageOpens() method in feature steps looks like some another driver used..

Related

getting the url as WebDriver instead of www.google.com

While performing the code the Test is getting failed as it is taking the actualtitle as webdriver
it has been made by using iedriver
a comparision is made to the base url and current url .
package newproject;
import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
public class Test1 {
`public static void main(String[] args`) {
// declaration and instantiation of objects/variables
String exePath = "D:\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe";
InternetExplorerDriverService.Builder serviceBuilder = new
InternetExplorerDriverService.Builder();
serviceBuilder.usingAnyFreePort(); // This specifies that sever can pick any available free port to start
serviceBuilder.usingDriverExecutable(new File(exePath));
//Tell it where you server exe is
serviceBuilder.withLogLevel(InternetExplorerDriverLogLevel.TRACE);//Specifies the log level of the server
serviceBuilder.withLogFile(new File("D:\\abc\\Documents\\logFile.txt")); //Specify the log file. Change it based on your system
InternetExplorerDriverService service = serviceBuilder.build();
//Create a driver service and pass it to Internet explorer driver instance
InternetExplorerDriver driver = new InternetExplorerDriver(service);
String baseUrl = "http://www.google.com";
StringBuffer expectedTitle = new StringBuffer("web driver");
String actualTitle = "";
driver.get("http://www.google.com");// get the actual value of the title
actualTitle = driver.getTitle();
System.out.println(actualTitle);
/*compare the actual title of the page with the expected one and prin the result as "Passed" or "Failed"*/
if (actualTitle.equalsIgnoreCase(baseUrl) )
{
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
// exit the program explicitly
System.exit(0);
}
How to get the page url instead of WebDriver??
I have just verified your code. It is taking the actual title as "Google" not webdriver.
This line is incorrect:
if (actualTitle.equalsIgnoreCase(baseUrl) ) {
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
You shouldn't compare title with the base URL. A comparison should be between expected title and actual title.

Selenium Firefox Browser has no internet connection

Selenium Firefox Browser has no internet connection :- when i try to run my selenium script using firefox , I get no internet connection error where as i do have good internet connection. Can anyone help?Thanks in advance
Here is the code, Its a dataprovider code to be able to create the data driven tests. But everytime i run this whether on firefox or be it chrome its not working
public class Test2 {
//webdriver object
WebDriver driver;
//test annotation
#Test(dataProvider="wordpressdata")
public void loginTest(String Username, String Password) throws InterruptedException{
//Setting the system property to use chrome exe
System.setProperty("webdriver.chrome.driver","C:\\Downloads\\Softwares\\chromedriver_win32\\chromedriver.exe" );
driver=new ChromeDriver();
driver.navigate().to("http://demosite.center/wordpress/wp-login.php");
Thread.sleep(5000);
driver.findElement(By.id("user_login")).sendKeys(Username);
driver.findElement(By.id("user_pass")).sendKeys(Password);
driver.findElement(By.xpath(".//*[#id='wp-submit']")).click();
}
//this is after method for driver quit
#AfterMethod
public void teardown(){
driver.quit();
}
//this is data provider
#DataProvider(name="wordpressdata")
public Object[][] passdata(){
Object[][] data = new Object[3][2];
data[0][0] = "Admin";
data[0][1] = "demo123";
data[1][0] = "Admin";
data[1][1] = "demo23";
data[2][0] = "Admin";
data[2][1] = "demo14";
return data;
}
}
This code is not letting me open it in either Firefox browser or Chrome.

UnReachableBrowserException in Chome with Selenium Webdriver

i am getting UnhandledBrowserException when trying the below code in chrome:
public class myClass {
public static void main(String[] args) {
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver", "C://Program Files (x86)//Google//Chrome//Application//chrome.exe");
WebDriver driver= new ChromeDriver();
String baseURL = "http://newtours.demoaut.com";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
// launch Firefox and direct it to the Base URL
driver.get(baseURL);
// get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page witht the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
//close Firefox
driver.close();
// exit the program explicitly
System.exit(0);
}
It is launching a new session in chrome but then throwing the exception. Any help would be highly appreciated.
I think you are hitting program executable instead of driver.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
It should be path to chrome driver not the chrome browser executable.
You can take a look at https://sites.google.com/a/chromium.org/chromedriver/getting-started

Wait for page loading using PageFactory C#

I'm using PageFactory in my selenium tests. And I've faced a problem in waiting for loading page. I'm not talking about an element on a page I'm talking about timeout of page loading.
So, I have a method like the following:
public MyProjectsPage ClickSaveAndCloseButton()
{
//Do something and click a button
SaveAndCloseButton.Click();
return new MyProjectsPage(Driver); //return new page
}
And when I'm waiting for returning new PageObject (in my case it is "MyProjectsPage") I got a timeout exception. So, where can I set a page loading timeout?
Actual mistake looks like this:
AutomatedTests.FrontEnd.SouvenirProduct.SouvenirTestExecution.OrderSouvenirWithAuthorization(ByCash,Pickup,True,Cup):
OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:7585/session/b68c04d1ead1fc78fe083e06cbece38f/element/0.46564483968541026-14/click timed out after 60 seconds.
----> System.Net.WebException : The operation has timed out
I have:
The latest version of WebDriver
And the latest version of ChromeDriver and the latest version of Chrome Browser
The mistake that is above apears int the next line:
return new MyProjectsPage(Driver); //return new page
I create my ChromeDriver the next way:
public DriverCover(IWebDriver driver)
{
_driver = driver;
_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
private readonly IWebDriver _driver;
1 note considering wait mechanisms on the page:
Take a couple of webElements and apply for them fluentWait() . That'll be explicit wait webdriver approach.
Another approach is to try out implicit wait like:
int timeToWait=10;
driver.manage().timeouts().implicitlyWait(timeToWait, TimeUnit.SECONDS);
Considering you pageObject code:
I would recommed you the following:
MyPage myPageInstance= PageFactory.initElements(driver, MyPage.class);
then you write the following method :
public MyPage clickSaveAndOtherActions(MyPage testPageToClick)
{
testPageToClick.clickFirstButton();
testPageToClick.clickSecondButton();
testPageToClick.closePoPup();
return testPageToClick; //return page in a new state
}
and if you wanna continue working (I mean update your page state) you do the following:
myPageInstance = clickSaveAndOtherActions(myPageInstance );
Hope this helps you. Thanks.
UPD : as I see from the log something looks wrong with remoteWebdriver server:
OpenQA.Selenium.WebDriverException : The HTTP request to the remote
WebDriver server for URL
http://localhost:7585/session/b68c04d1ead1fc78fe083e06cbece38f/element/0.46564483968541026-14/click
timed out after 60 seconds. ----> System.Net.WebException : The
operation has timed out
Also, I'd recommend you to double check you driver method init. I'm using the following piece of java code for driver init (UI , chrome instance, selenium grid+ hub nodes test architecture):
public static WebDriver driverSetUp(WebDriver driver) throws MalformedURLException {
DesiredCapabilities capability = DesiredCapabilities.chrome();
log.info("Google chrome is selected");
//System.setProperty("webdriver.chrome.driver", System.getProperty("user.home")+"/Documents/Tanjarine/chromedriver");
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
capability.setBrowserName("chrome");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
String webDriverURL = "http://" + environmentData.getHubIP() + ":" + environmentData.getHubPort() + "/wd/hub";
driver = new RemoteWebDriver(new URL(webDriverURL), capability);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1920, 1080));
return driver;
}
What you should really be doing when using the PageFactory pattern is when initialising your Page you should be using a constructor to initialise the elements.
public MyProjectsPage ClickSaveAndCloseButton()
{
//Do something and click a button
//I am guessing this is taking you to the MyProjectsPage
SaveAndCloseButton.Click();
return new MyProjectsPage(Driver); //return new page
}
public class MyProjectsPage
{
[FindsBy(How = How.Id, Using = "yourId")]
public IWebElement AWebElement { get; set; }
private IWebDriver WebDriver;
public MyProjectsPage (IWebDriver webDriver)
{
WebDriver = webDriver;
PageFactory.InitElements(WebDriver, this);
}
}
When you return the page, all elements using the FindsBy attribute will be initialised.
Update:
set this property on the driver when you initialise it:
WebDriver.Manage().Timeouts().SetPageLoadTimeout(timespan)
// Wait Until Object is Clickable
public static void WaitUntilClickable(IWebElement elementLocator, int timeout)
{
try
{
WebDriverWait waitForElement = new WebDriverWait(DriverUtil.driver, TimeSpan.FromSeconds(10));
waitForElement.Until(ExpectedConditions.ElementToBeClickable(elementLocator));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found in current context page.");
throw;
}
}
// Wait For Page To Load
public static void WaitForPage()
{
new WebDriverWait(DriverUtil.driver, MyDefaultTimeout).Until(
d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));
}

Unable to find the locator with Link Text test case getting failed

I am not able find the locator with anchor tag. Using xpath doesn't give the result.
Here is the HTML code :
<a id="sme1" class="item" href="/website-url" onclick="swapClasses('sme1')"
target="main" style="background-color:
transparent;">Mailboxes</a>
Selenium code :
private static final String baseURL = "http://10.112.75.248/";
private static final String adminURL = baseURL + "manager/";
private static String username = "admin";
private static String password = "default";
WebDriver driver ;
SearchElement searchEl;
#BeforeTest
public void setBaseURL(){
driver = new FirefoxDriver();
driver.get(adminURL);
searchEl = new SearchElement();
}
#Test(priority=0)
public void verifyLoginSuccessFull() {
searchEl.getElementsByXpath(driver, "//input[#name='username']").sendKeys(username);
searchEl.getElementsByXpath(driver, "//input[#name='password']").sendKeys(password);
searchEl.getElementsByXpath(driver, "//input[#name='submit']").submit();
String expected = "Selenium Home Page";
Assert.assertEquals(driver.getTitle(), expected);
}
#Test(priority=1)
public void addMailbox(){
//WebDriverWait wait = new WebDriverWait(driver, 1000);
//wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Mailboxes']")));
//driver.findElement(By.id("smel")).click();
searchEl.getElementsByLinkText(driver, "//a[text()='Mailboxes']").click(); //This line of code not fetching the locator.
}
SearchElement class used as a controller :
public class SearchElement {
public WebElement getElementsByXpath(WebDriver driver,String locator){
WebElement el = driver.findElement(By.xpath(locator));
return el;
}
public WebElement getElementsByLinkText(WebDriver driver,String locator){
WebElement el = driver.findElement(By.linkText(locator));
return el;
}
}
Actual Error :
Unable to locate element: {"method":"link
text","selector":"//a[text()='Mailboxes']"}
Note : The URL is different when the user logs in and when the user is presented the login page. I dont know it might be a problem.
Please help in advance.
By.linkText() method expects link text as parameter, but in that code you're passing XPath string. Try to pass the link text instead :
searchEl.getElementsByLinkText(driver, "Mailboxes").click();
try this.
//a[.='Mailboxes']
This is a text base search and "." inside the xpath navigates you to the parent