Friday 2 June 2017

Selenium WebDriver : Using Navigation methods

Want to navigate to a particular Website (or URL), and you are feeling a bit lazy to open a browser, type in the website URL again and again.. and again.. whenever you want to ? Welcome to another post in which we are going to see how we can use selenium WebDriver to open a Website. 

If you are new to Selenium, check out my previous posts on how to set up the environment to get started with Selenium WebDriver.


Selenium WebDriver provides us with different methods such as get() and navigate(), which can be used directly to get the website (or URL) specified as parameters with these methods.


1 - Using get() method :

     Following code snippet can be used to get a webpage after initializing Web Browser :

 

public class Sample {
public static void main(String[] args) {
//Initialize Browser
System.setProperty("webdriver.gecko.driver", "E:\\AllJARS\\Selenium_Driver_Servers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();


driver.get("https://www.google.com/");
}
}


Note : get() takes the URL of the website as a parameter.

 


2- Using navigate() method :

      Following code snippet can be used as an alternative method to get() :

 

public class Sample {
public static void main(String[] args) {
//Initialize Browser
System.setProperty("webdriver.gecko.driver", "E:\\AllJARS\\Selenium_Driver_Servers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("https://www.google.com/");

driver.findElement(By.cssSelector("#_eEe a")).click();
driver.navigate().back();
driver.navigate().forward();
}
}


Note : navigate().to() takes the URL of the website as a parameter.

 

If you use navigate().to() method to get a web page, it also allows you to use couple of more methods to navigate through the history of the Web Browser. So you would be able to go back or forward, as far as Web Browser history is concerned.

 

Using back() : (To navigate back in history)

driver.navigate().back();

 

Using forward() : (To navigate forward in history)

driver.navigate().forward();

 

Above 2 mentioned methods (back()  and forward()) allows you to navigate through the history of the Web Browser as and when required.

 

That's it in this short post about navigating to Web Pages using Selenium WebDriver. Feel free to comment in the comments section if you have any queries / suggestions.

Stay tuned for more interesting posts about Test Automation using Selenium.

Happy Learning.  

YouTube Channel : Click Here

No comments:

Post a Comment