Getting the URL of the current page using Selenium WebDriver - java

I'm attempting to get the URL of the currently open page. I am using Selenium WebDriver and Java.
I am accessing the current URL via:
WebDriver driver = new WebDriver();
String url = driver.getCurrentUrl();
however, the URL does not appear to actually reflect where I currently am.
My current test case involves going to the NYT website and then clicking on the "Technology" link. However, url appears to always be http://www.nytimes.com/, regardless of the URL that is displayed in the address bar.
How do I actually access the value of the URL that's in the address bar so I can tell what page I'm actually on?

Put sleep. It will work. I have tried.
The reason is that the page wasn't loaded yet.
Check this question to know how to wait for load - Wait for page load in Selenium

Related

driver.get(url) vs driver.navigate().to(url);

Google's Answer:
get() is used to navigate particular URL(website) and wait till page load. driver. navigate() is used to navigate to particular URL and does not wait to page load.
Selenium Documentation:
The document.readyState property of a document describes the loading state of the current document. By default, WebDriver will hold off on responding to a driver.get() (or) driver.navigate().to() call until the document ready state is complete
My query is in Google it was said, navigate method doesnot wait till the page loads which was not in line with the point added from Selenium Documentation.
Please help me to understand.
The first thing we do when run the script is to open the browser and load the web page. We use commonly driver.get(“url”); to load the webpage. Every time we use this command, the page will be refreshed.
We can also use driver.navigate().to(“url’); to load the webpage. Both the commands work in the same way in terms of behavior. But the navigate().to() also have the other functions such as navigate().forward(), navigate().back() and navigate().refresh().
So the difference is driver.get() never stores history whereas driver.navigate().to() stores browser history so as to be used for other commands forward and back etc.
In single page applications while navigate().to() navigates to the page by changing URL like doing forward/backward, get() refreshes page.
More info here - Difference between webdriver.get() and webdriver.navigate()
In simple words get() method in the WebDriver interface extends the SearchContext and is defined as:
/**
* Load a new web page in the current browser window. This is done using an HTTP POST operation,
* and the method will block until the load is complete.
* This will follow redirects issued either by the server or as a meta-redirect from within the
* returned HTML.
* Synonym for {#link org.openqa.selenium.WebDriver.Navigation#to(String)}.
*/
void get(String url);
Hence you can use:
driver.get("https://www.google.com/");
On the other hand, navigate() is the abstraction which allows the WebDriver instance i.e. the driver to access the browser's history as well as to navigate to a given URL. The methods along with the usage are as follows:
to(java.lang.String url): Load a new web page in the current browser window.
driver.navigate().to("https://www.google.com/");
to(java.net.URL url): Overloaded version of to(String) that makes it easy to pass in a URL.
refresh(): Refresh the current page.
driver.navigate().refresh();
back(): Move back a single "item" in the browser's history.
driver.navigate().back();
forward(): Move a single "item" forward in the browser's history.
driver.navigate().forward();
//Convenient
driver.get("https://selenium.dev");
//Longer way
driver.navigate().to("https://selenium.dev");
28/08/2022
There is no difference between the two, just that one is the long form and the other is the short form of Java.
https://www.selenium.dev/documentation/webdriver/browser/navigation/

Object error Firefox when automating with eclipse

I am getting an [object Object] error when I try to automate a web page.I am using Firefox v39 as later version cause problems in online signature. My code did work properly for Firefox v63.
Code is simply to open a webpage, enter username and password, login, and then navigate to a page.
I have provided a Screenshot of the error. Please check.
enter image description here
CODE-
System.setProperty("webdriver.firefox.marionette","F:\\firefoxdriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("LINK");
driver.manage().window().maximize();
driver.findElement(By.id("username")).sendKeys("USERNAME");
driver.findElement(By.id("password")).sendKeys("PASS");
driver.findElement(By.xpath("//button[#class='btn btn-success btn-logging']")).click();
WebElement kyc =driver.findElement(By.xpath("/html/body/div[1]/div/div/ul/li[2]/ul/li[6]/a"));
String href=kyc.getAttribute("Href");//get link to approval
driver.navigate().to(href);
This happens when the page is not completely loaded and hence an object is not found. This could happen due to slow net, slow site.
Solution-
Increase the wait, used static wait and keep increasing it unless it does not occur.

Using Selenium on https web application that runs over vpn

First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.
My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.
My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.
If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
// I tried also with this code bellow in comment, but it did not work, it did not even get to login page
//WebDriverWait wait = new WebDriverWait(driver, 10);
//Alert alert = wait.until(ExpectedConditions.alertIsPresent());
//alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
driver.get("https://Application_login_page.com");
driver.findElement(By.xpath(".//*[#id='login']")).click();
driver.findElement(By.xpath("[#id='login']")).sendKeys("Username");
}
if it's possible, is there a way to start Selenium testing on application that is already opened and prepared (logged) in browser?
Try using firefox profile. Since selenium open fresh instance of browser by default. You can use your own firefox frofile.
This is a code to implement a profile, which can be embedded in the selenium code.
ProfilesIni profile = new ProfilesIni();
// this will create an object for the Firefox profile
FirefoxProfile myprofile = profile.getProfile("default");
// this will Initialize the Firefox driver
WebDriver driver = new FirefoxDriver(myprofile)
It will also maintain the session means you are already login to the application in firefox(default profile). Then if you execute the script, you will see that you are already logged in to the application.
There is no way to open already authorised page, you have to have to pass username and password through selenium script.
You may use below code to do the authentication
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));

Avoid the execution stop while browsing in Selenium WebDriver

I need help for this thing that's driving me crazy.
I want to check the browser url in and endless loop, waiting a little (Thread.Sleep) between a loop and another, to not overload the CPU. Then, if the browser url is what I need, I want to add/change/remove an element through Javascript before the page is fully loaded, otherwise the person who uses this could see the change. (I don't need help for the javascript part)
But there's a problem: it seems that in Selenium Webdriver when I navigate to a page (with .get(), .navigate().to() or also directly from the client) the execution is forced to stop until the page is loaded.
I tried to set a "fake" timeout, but (at least in Chrome) when it catches the TimeoutException, the page stops loading. I know that in Firefox there's an option for unstable loading, but I don't want to use it because my program isn't only for Firefox.
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(0, TimeUnit.MILLISECONDS); // Fake timeout
while (true) {
try {
// If the url (driver.getCurrentUrl()) is what I want, then execute javascript without needing that page is fully loaded
// ...
// ...
}
catch (TimeoutException e) {
// It ignores the Exception, but unfortunately the page stops loading.
}
Thread.sleep(500); // Then wait some time to not overload the cpu
}
}
I need to do this in Chrome, and if possible with Firefox and Internet Explorer. I'm programming in Java. Thanks in advance.
Selenium is designed to stop once the webpage is loaded into the browser so that it can proceed with execution.
In your case there are two options:
1) If the browser url will change automatically (ajax) at an arbitrary time, then just keep getting browser url until your condition satisfies.
while(currentURL.equals("Your Condition")){
currentURL = driver.getCurrentUrl();
Thread.sleep(2000);
}
2) If the browser needs to be refreshed use the refresh method in a loop until you get your desired url
while(currentURL.equals("Your Condition")){
driver.navigate().refresh();
currentURL =
Thread.sleep(2000);
}
As know, if user tried with driver.get("url");, selenium waits until page is loaded (may not be very long). so if you want to do some thing on navigate to URL without waiting total load time use below code instead of get or navigate
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("window.open('http://seleniumtrainer.com/components/buttons/','_self');");
After this used
driver.findElement(By.id("button1")).click();
to click on button but i am getting no such element exception, so i am expecting its not waiting for page load. so times page loading very quick and click working fine.
i hope this will help you to figure it out your issue at start up. for loop i hope solution already provided.
Thanks

Difference between webdriver.get() and webdriver.navigate()

What is the difference between get() and navigate() methods?
Does any of this or maybe another method waits for page content to load?
What do I really need is something like Selenium 1.0's WaitForPageToLoad but for using via webdriver.
Any suggestions?
Navigating
The first thing you’ll want to do with WebDriver is navigate to a page. The normal way to do this is by calling get:
driver.get("http://www.google.com");
WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.
Navigation: History and Location
Earlier, we covered navigating to a page using the get command (driver.get("http://www.example.com")) As you’ve seen, WebDriver has a number of smaller, task-focused interfaces, and navigation is a useful task. Because loading a page is such a fundamental requirement, the method to do this lives on the main WebDriver interface, but it’s simply a synonym to:
driver.navigate().to("http://www.example.com");
To reiterate: navigate().to() and get() do exactly the same thing. One's just a lot easier to type than the other!
The navigate interface also exposes the ability to move backwards and forwards in your browser’s history:
driver.navigate().forward();
driver.navigate().back();
(Emphasis added)
They both seems to navigate to the given webpage and quoting #matt answer:
navigate().to() and get() do exactly the same thing.
Single-Page Applications are an exception to this.
The difference between these two methods comes not from their behavior, but from the behavior in the way the application works and how browser deal with it.
navigate().to() navigates to the page by changing the URL like doing forward/backward navigation.
Whereas, get() refreshes the page to changing the URL.
So, in cases where application domain changes, both the method behaves similarly. That is, page is refreshed in both the cases. But, in single-page applications, while navigate().to() do not refreshes the page, get() do.
Moreover, this is the reason browser history is getting lost when get() is used due to application being refreshed.
Originally answered: https://stackoverflow.com/a/33868976/3619412
driver.get() : It's used to go to the particular website , But it doesn't maintain the browser History and cookies so , we can't use forward and backward button , if we click on that , page will not get schedule
driver.navigate() : it's used to go to the particular website , but it maintains the browser history and cookies, so we can use forward and backward button to navigate between the pages during the coding of Testcase
Not sure it applies here also but in the case of protractor when using navigate().to(...) the history is being kept but when using get() it is lost.
One of my test was failing because I was using get() 2 times in a row and then doing a navigate().back(). Because the history was lost, when going back it went to the about page and an error was thrown:
Error: Error while waiting for Protractor to sync with the page: {}
driver.get() is used to navigate particular URL(website) and wait till page load.
driver.navigate() is used to navigate to particular URL and does not wait to page load. It maintains browser history or cookies to navigate back or forward.
As per the javadoc for get(), it is the synonym for Navigate.to()
View javadoc screenshot below:
Javadoc for get() says it all -
Load a new web page in the current browser window. This is done using
an HTTP GET operation, and the method will block until the load is
complete. This will follow redirects issued either by the server or as
a meta-redirect from within the returned HTML. Should a meta-redirect
"rest" for any duration of time, it is best to wait until this timeout
is over, since should the underlying page change whilst your test is
executing the results of future calls against this interface will be
against the freshly loaded page. Synonym for
org.openqa.selenium.WebDriver.Navigation.to(String).
navigate().to() and get() will work same when you use for the first time. When you use it more than once then using navigate().to() you can come to the previous page at any time whereas you can do the same using get().
Conclusion: navigate().to() holds the entire history of the current window and get() just reload the page and hold any history.
For what it's worth, from my IE9 testing, it looks like there's a difference for URLs that contain a hashbang (a single page app, in my case):
http://www.example.com#page
The driver.get("http://www.example.com#anotherpage") method is handled by the browser as a fragment identifier and JavaScript variables are retained from the previous URL.
While, the navigate().to("http://www.example.com#anotherpage") method is handled by the browser as a address/location/URL bar input and JavaScript variables are not retained from the previous URL.
There are some differences between webdriver.get() and webdriver.navigate() method.
get()
As per the API Docs get() method in the WebDriver interface extends the SearchContext and is defined as:
/**
* Load a new web page in the current browser window. This is done using an HTTP POST operation,
* and the method will block until the load is complete.
* This will follow redirects issued either by the server or as a meta-redirect from within the
* returned HTML.
* Synonym for {#link org.openqa.selenium.WebDriver.Navigation#to(String)}.
*/
void get(String url);
Usage:
driver.get("https://www.google.com/");
navigate()
On the other hand, navigate() is the abstraction which allows the WebDriver instance i.e. the driver to access the browser's history as well as to navigate to a given URL. The methods along with the usage are as follows:
to(java.lang.String url): Load a new web page in the current browser window.
driver.navigate().to("https://www.google.com/");
to(java.net.URL url): Overloaded version of to(String) that makes it easy to pass in a URL.
refresh(): Refresh the current page.
driver.navigate().refresh();
back(): Move back a single "item" in the browser's history.
driver.navigate().back();
forward(): Move a single "item" forward in the browser's history.
driver.navigate().forward();
driver.get("url") and driver.navigate( ).to("url") both are same/synonymous.
to("url") internally calling get("url") method. Please find the below image for reference.
Either of them does not store history - this is the wrong information that is available on most of the blogs/websites.
Below, statements 1, 2, and 3, 4 will do the same things i.e land in the given URL.
statemnt 1: driver.get("http://www.google.com");
statemnt 2: driver.navigate( ).to("http://www.amazon.in");
statemnt 3: driver.get("http://www.google.com");
statemnt 4: driver.get("http://www.amazon.in");
Only navigate() can do different things i.e. moving back, forward, etc. But not the to("url") method.
Otherwise you prob want the get method:
Load a new web page in the current browser window. This is done using an
HTTP GET operation, and the method will block until the load is complete.
Navigate allows you to work with browser history as far as i understand it.
Both perform the same function but driver.get(); seems more popular.
driver.navigate().to(); is best used when you are already in the middle of a script and you want to redirect from current URL to a new one. For the sake of differentiating your codes, you can use driver.get();to launch the first URL after opening a browser instance, albeit both will work either way.
CASE-1
In the below code I navigated to 3 different URLs and when the execution comes to navigate command, it navigated back to facebook home page.
public class FirefoxInvoke {
#Test
public static void browserInvoke()
{
System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
WebDriver driver=new FirefoxDriver();
System.out.println("Before"+driver.getTitle());
driver.get("http://www.google.com");
driver.get("http://www.facebook.com");
driver.get("http://www.india.com");
driver.navigate().back();
driver.quit();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
browserInvoke();
}
}
CASE-2:
In below code, I have used navigate() instead of get(), but both the snippets(Case-1 and Case-2) are working exactly the same, just the case-2 execution time is less than of case-1
public class FirefoxInvoke {
#Test
public static void browserInvoke()
{
System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
WebDriver driver=new FirefoxDriver();
System.out.println("Before"+driver.getTitle());
driver.navigate().to("http://www.google.com");
driver.navigate().to("http://www.facebook.com");
driver.navigate().to("http://www.india.com");
driver.navigate().back();
driver.quit();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
browserInvoke();
}
}
So the main difference between get() and navigate() is, both are
performing the same task but with the use of navigate() you can move
back() or forward() in your session's history.
navigate() is faster than get() because navigate() does not wait for
the page to load fully or completely.
driver.get(url) and navigate.to(url) both are used to go to particular web page. The key difference is that
driver.get(url): It does not maintain the browser history and cookies and wait till page fully loaded.
driver.navigate.to(url):It is also used to go to particular web page.it maintain browser history and cookies and does not wait till page fully loaded and have navigation between the pages back, forward and refresh.
To get a better understanding on it, one must see the architecture of Selenium WebDriver.
Just visit https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
and search for "Navigate to a new URL." text. You will see both methods GET and POST.
Hence the conclusion given below:
driver.get() method internally sends Get request to Selenium Server Standalone. Whereas driver.navigate() method sends Post request to Selenium Server Standalone.

Categories