Home » selenium-tutorial

Category Archives: selenium-tutorial

Newly Updated Posts

Scroll Up or Down in Selenium

Previous tutorial we have learned popup window handling and now we will learn Scroll Up or Down in Selenium

What is Scrolling?

Scrolling is nothing but moving the screen in horizontal and vertical direction.

How to Scroll Up or Down in Selenium?

If a particular element is not visible in current web application window because of which we need scrolling to view the element in a particular direction .

Scrolling in web page is performed in two ways horizontal scrolling and vertical scrolling.Lets discuss both of them in details.

What is Vertical Scrolling ?

1) Vertical Scrolling: It can be performed when we try to scroll the web page in downward direction with its pixels.The syntax for vertical scrolling is as below:

JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments); 

Lets consider a scenario to perform vertical scrolling:

  • Open a web application www.code2test.com
  • Click to selenium menu.
  • Now perform the vertical scrolling.
package SeleniumArchitecture;
import java.util.Base64;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
public class Scrolling_using_selenium {
public static void main(String[] args) throws InterruptedException {// System property of the Chrome driver

System.setProperty( "webdriver.chrome.driver","C:\\Users\\XXXXX\\Desktop\\Eclipse_Installer\\GeckoDriver\\chromedriver.exe");	  
// Create oject of chrome driver WebDriver driver = new ChromeDriver();
 Thread.sleep(3000);       
 ChromeDriver    driver= new ChromeDriver();	  
 driver.manage().window().maximize(); Thread.sleep(3000);
 driver.get("https://code2test.com/");
 //click to selenium menu
 driver.findElement(By.xpath("//*[@id='menu-post-1']/li[3]/a")).click();
 Thread.sleep(3000);
 JavascriptExecutor js = (JavascriptExecutor) driver;
 //Scroll vertical direction 100 pixel 
 js.executeScript("window.scrollBy(0,1000)");		
	}
}

ScrollIntoView():This code will scroll in the web page until the particular element gets visible to the current page. It keeps on scrolling in the page till the visibility on the screen. The Syntax of ScrollIntoView() is below:

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript("arguments[0].scrollIntoView();",Element );

Lets consider a scenario to perform vertical scrolling:

  • Open a web application www.code2test.com
  • Click to selenium menu.
  • Now perform the vertical scrolling and .
package SeleniumArchitecture;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Scrolling_using_selenium {

public static void main(String[] args) throws InterruptedException {// System property of the Chrome driver

 System.setProperty( "webdriver.chrome.driver","C:\\Users\\XXXXXX\\Desktop\\Eclipse_Installer\\GeckoDriver\\chromedriver.exe");	  
// Create oject of chrome driver WebDriver driver = new ChromeDriver();
 Thread.sleep(3000);       
 ChromeDriver    driver= new ChromeDriver();	  
 driver.manage().window().maximize(); Thread.sleep(3000);
 driver.get("https://code2test.com/");
//click to selenium menu
 driver.findElement(By.xpath("//*[@id='menu-post-1']/li[3]/a")).click();
 Thread.sleep(3000);
//Xpath from select From Date 
WebElement selectFromDateTitle= driver.findElement(By.xpath("//*[@id='post-30']/div/div[8]//li[3]/a"));

 JavascriptExecutor js = (JavascriptExecutor) driver;
		  
//Scroll vertical direction 100 pixel 
js.executeScript("arguments[0].scrollIntoView();", selectFromDateTitle);		
	}
}

In the above code “selectFromDateTitle” is the locator of an element.

“argument[0]” is the index of page which stars from “0”

Scroll up or down in selenium

What is Horizontal Scrolling?

2) Horizontal scrolling: In horizontal scrolling the scrolling is performed on left to right Or right to left on web page, the horizontal scrolling can be done by coding by providing the x-axis co-ordinates on ScrollBy( ) method. Let see the syntax below.

executeScript(“window.scrollBy(x-pixels,y-pixels)”);

Also horizontal scrolling can be performed by ScrollIntoView() method, where an scrolling is performed till the element is available on the current page.

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript("arguments[0].scrollIntoView();",Element );

On next topic we will cover integration part in selenium webdriver.

Unexpected popup window handling using selenium

In this tutorial we will learn unexpected popup window handling using selenium. Also we will learn how to handle multiple window and its window id as per the requirement of automation script.

How to resolve Unexpected popup window issue using Selenium?

In a web application we sometimes come across an issue where we get unexpected popup windows. We see other windows open when we try opening single application URL. In such cases it becomes tough to work with main window and sometimes our automation scripts gets stuck or failed.

To overcome this Unexpected issue we handle it in our automation script so that automation script runs smoothly without any hurdles.

The solution to overcome with such unexpected popup windows is to get window ids of unexpected window and take the control to that window ids and close them using selenium.

Consider the below scenario:

  • Open the web application of online job portal https://www.naukri.com/
  • After it opens, it opens with two other window.
  • Close both the other window
  • Now take the control of driver to main page
  • print the title of main page

Complete Code of the above scenario.

package SeleniumArchitecture;
import java.util.Base64;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.chrome.ChromeDriver;
public class UnExpectedPopUpWindow_Handle {

public static void main(String[] args) throws InterruptedException {

System.setProperty( "webdriver.chrome.driver","C:\\Users\\XXXXX\\Desktop\\Eclipse_Installer\\GeckoDriver\\chromedriver.exe");	  
// Create oject of chrome driver WebDriver driver = new ChromeDriver();
 Thread.sleep(3000);       
 ChromeDriver    driver= new ChromeDriver();	  
 driver.manage().window().maximize(); Thread.sleep(3000);
 driver.get("https://www.naukri.com/");
		  
 Set<String> windowIds=driver.getWindowHandles();
			 
 System.out.println("Total windows------------>"+windowIds.size());
			 
 Iterator<String> itera= windowIds.iterator();
 if(windowIds.size()==3) {					  
 String MainWindowID = itera.next();
 String secondWindowID = itera.next();
 String thirdWindowID = itera.next();
			
 driver.switchTo().window(secondWindowID);
 driver.close();
 driver.switchTo().window(thirdWindowID);
 driver.close();	
 driver.switchTo().window(MainWindowID);		
 String mainWindowTitle = driver.getTitle();
System.out.println("Title for the main window is ------ >"+mainWindowTitle);			  
		  }
	}
}

Code explanation:

  • In selenium, we can capture the window ids of multiple windows using driver.getWindowHandles(), it returns a set and add all the window ids present in the current driver instance.

code -> Set windowIds=driver.getWindowHandles();

  • Now its time to iterate the window ids for this we call iterator, in set we iterate using iterator()

code-> Iterator itera= windowIds.iterator();

  • Now apply an if statement having condition that window ids are equal to 3 (note we have 3 window appearing to this application) and click to next till iteration to the window ids which need to be closed. and on pointing to that close the driver and then switch to main window

Code->

if(windowIds.size()==3) {

String MainWindowID = itera.next();
String secondWindowID = itera.next();
String thirdWindowID = itera.next();
driver.switchTo().window(secondWindowID);
driver.close();
driver.switchTo().window(thirdWindowID);
driver.close();
driver.switchTo().window(MainWindowID);
 String mainWindowTitle = driver.getTitle();

 System.out.println("Title for the main window is --------------->"+mainWindowTitle);
      }

So till now we have learned how unexpected popup issue is handled using selenium. In next topic we will learn more such topics related to selenium web-driver.

How to select date from DatePicker calender

Previous Topic, In this tutorial we will learn How to select date from DatePicker calender, date from date picker calendar step by step.

How to select date from DatePicker calender using selenium?

Date Picker in just a selection of date from calendar by selecting a number.

On selecting the number (date), the date appears as text field in DD/MM/YYYY format or other format defined in code.

select date from Date Picker Using Selenium

To understand date picker lets consider a scenario and code for date picker.

Complete Code for the above scenario:

public static void datePicker(String enterDate, WebDriver driver) throws ParseException {

Date current = new Date();
SimpleDateFormat dFormat = new SimpleDateFormat("d/MM/yyyy");
try {
Date dateToSelect = dFormat.parse(enterDate);

String day = new SimpleDateFormat("d").format(dateToSelect);
String month = new SimpleDateFormat("MMMM").format(dateToSelect);
String year = new SimpleDateFormat("yyyy").format(dateToSelect);

System.out.println(day + "     " + month + "     " + year + "      ");

String requiredMonth = month + " " + year;

System.out.println("Required month Year-------------" + requiredMonth);

WebElement clickDateField = driver.findElement(By.xpath("//input[@name='txtDate']"));
clickDateField.click();

Boolean flag = true;

while (flag) {

String monthoncalenderHeader = driver.findElement(By.xpath("//div[@class='ui-datepicker-title']"))
.getText();

if (requiredMonth.equalsIgnoreCase(monthoncalenderHeader)) {
					driver.findElement(By.xpath("//a[text()='" + day + "']")).click();

flag = false;

break;
} else {

if (dateToSelect.compareTo(current) > 0)

driver.findElement(By.xpath("//a[@data-handler='next']")).click();

else if (dateToSelect.compareTo(current) < 0)						driver.findElement(By.xpath("//a[@data-handler='prev']")).click();
				}
}
} catch (Exception e) {
e.printStackTrace();
}

}

To Call the method simply call datePicker(String date, driver); to any of the automation script, just simply pass date(in DD/MM/YYYY) format and driver instance as second parameter.

Explanation of above code line by line:

  • Firstly create the object of date class and assign in to DD/MM/YYYY format as below in code
Date current = new Date();
SimpleDateFormat dFormat = new SimpleDateFormat("d/MM/yyyy");
  • Under try catch block parse the date extract or bifurcate the date, month and year in a String from .format method also take the month and year in a string as the per the calender header in web application
Date dateToSelect = dFormat.parse(enterDate);

String day = new SimpleDateFormat("d").format(dateToSelect);
String month = new SimpleDateFormat("MMMM").format(dateToSelect);
String year = new SimpleDateFormat("yyyy").format(dateToSelect);

System.out.println(day + "          " + month + "     " + year + "         ");

String requiredMonth = month + " " + year;
  • Now click to the text field of calender, so that the calender get populated
WebElement clickDateField = driver.findElement(By.xpath("//input[@name='txtDate']"));
clickDateField.click();
  • Now open a while loop and create a condition on if statement that if the required month year is equal to the month year displayed in header of calendar in web application then click to the date on that window if not move to else condition
  • Under Else Condition if the required month year is greater that the month year present in the header displayed in the calendar on web application the click to next button, and if its less than click to previous button.
Boolean flag = true;
while (flag) {

String monthoncalenderHeader = driver.findElement(By.xpath("//div[@class='ui-datepicker-title']"))
.getText();

if (requiredMonth.equalsIgnoreCase(monthoncalenderHeader)) {				driver.findElement(By.xpath("//a[text()='" + day + "']")).click();

flag = false;

break;
} else {

if (dateToSelect.compareTo(current) > 0)					driver.findElement(By.xpath("//a[@data-handler='next']")).click();
else if (dateToSelect.compareTo(current) < 0)						driver.findElement(By.xpath("//a[@data-handler='prev']")).click();
}	
}

In the above tutorial, we have learned date picker in selenium, next we will learn advance topics in selenium webdriver

Password Encryption and Decryption in selenium

Previous Topic, In this tutorial we will learn password Encryption and Decryption techniques in selenium webdriver, its implementation and advantage in selenium script.

Whats is Password Encryption and Decryption?

Password Encryption and Decryption is selenium web driver is a technique in selenium , of encrypting the password or the user credentials so that it cannot be read by unauthorized individual from directly accessing it or in other words encryption of data is binded in such way that different individual or unauthorized person cannot understand it in simple text .

Similarly Decryption data is the technique to decrypt or converting of data in the text so that the computer can understand the data along with the individual.

How to achieve encryption and decryption in automation script ?

Encryption and Decryption of a String or any other text can be performed in java using Base64 Class, which is part of java.util package and contains method from encryption and decryption of data.

Lets understand encryption more by coding:

package SeleniumArchitecture;

import java.util.Base64;

public class EncrptionAndDecryption {

public static void main(String[] args) {

String encrptData= "Password";
		
byte[] encodedBytes = Base64.getEncoder().encode(encrptData.getBytes());
		
System.out.println("encodedBytes --------------->" + new String(encodedBytes));

}
}

Code in Eclipse along with Output:

Password Encryption and Decryption in selenium

Lets understand Decryption more by coding:

package SeleniumArchitecture;
import java.util.Base64;
public class EncrptionAndDecryption {

public static void main(String[] args) {

//String encrptData= "Password";
String decrptData  ="UGFzc3dvcmQ=";
		
byte[] decodeBytes = Base64.getDecoder().decode(decrptData.getBytes());
		
System.out.println("decodedBytes --------------->" + new String(decodeBytes));

	}
}
Password Encryption and Decryption in selenium

Above tutorials we understand How Encryption and Decryption in selenium works, the encryption and decryption on a string using base64 class.

Facebook-> https://www.facebook.com/code2test/?modal=admin_todo_tour

implicit,explicit And fluent wait in selenium

Wait in selenium Webdriver plays a crucial role in excution of Automation script,So in this tutorial we will discuss all the waits that can be provided by selenium for the smooth script execution.

What is implicit, explicit & Fluent wait in selenium?

As we know that the Web application are been developed by the developers in different technology like javascript etc., so these application takes different time span for the loading of the web page, there may be many other reason for the delay in loading of web page that can be slowness or environmental issue etc.

So to overcome and make our automation script wait for the time required for web page to load and prevends from ‘ ElementNotVisibleException‘ we use wait commands.

There are basically 3 types of wait in selenium webdriver these are:

1) Implicit wait: By implementing the implicit wait in selenium webdriver automation script, the script wait for certain time span for the webpage to load and execution do not gets effected. The syntax for implicit wait is below.

Syntax:

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

This command accepts the 2 parameters which is Timeout in integer and measurement of time period these are SECONDS, MINUTES, MILISECOND etc.

2) Explicit wait:

Double Click and Right Click using selenium

Previous Topic, In this tutorial we will learn how to Double Click and Right Click in selenium,selenium has its pre-defined classes because of which we perform operation like keyboard operations, mouse movements like drag and drop, mouse hover etc.

Double Click and Right click using selenium

How to perform Double click in selenium?

Double click in selenium and Right Click is perforrmed by Action class. In Action class we can perform operation of keyboard and mouse actions. Find below code to double click by action class.

Actions mouseActn=new Actions(driver);						 						  
WebElement locator =driver.findElement(By.id("ID"));						 mouseActn.doubleClick(locator).build().perform();

Description on above code:

  • Firstly we create the object of Action class and pass the driver as a parameter to it
  • Create the locator of the element to perform double click.
  • call the doubleClick method from the instance variable of action class the pass the locator as a parameter along with build().perform();

Consider a scenario to under and perform double click to understand more better

package SeleniumArchitecture;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class FiestTestScriptChrome {
public Boolean Flag =false;
public static void main(String[] args) throws InterruptedException  {
//System property of the Chrome driver 
			  System.setProperty("webdriver.chrome.driver","C:\\Users\\XXXXXX\\Desktop\\Eclipse_Installer\\GeckoDriver\\chromedriver.exe");
 // Create oject of chrome driver 
 WebDriver driver =  new ChromeDriver();
Thread.sleep(3000);			driver.get("http://demo.guru99.com/test/simple_context_menu.html");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
WebElement clickBouble =driver.findElement(By.xpath("//*[@id=\"authentication\"]/button"));
 Actions mouseActn=new Actions(driver);
Thread.sleep(3000);
mouseActn.doubleClick(clickBouble).build().perform();
 Thread.sleep(3000);		  
driver.quit();
}

}

Right Click in Selenium

Right Click in selenium can be performed by Action Class in selenium.The Right Click in selenium is called as context Click. The syntax for context click in selenium is below:

Actions mouseActn=new Actions(driver);
WebElement clickContext =driver.findElement(By.id("ID"));
 Thread.sleep(3000);						 mouseActn.contextClick(clickContext).build().perform();

Description of above code is below:

  • Firstly we create the object of Action class and pass the driver as a parameter to it
  • Create the locator for the element to right click .
  • call the contextClick method from the instance variable of action class the pass the locator as a parameter along with build().perform();

Consider a scenario to under and perform right click to understand more better :

package SeleniumArchitecture;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class FiestTestScriptChrome {

public static void main(String[] args) throws InterruptedException  {
//System property of the Chrome driver			  System.setProperty("webdriver.chrome.driver","C:\\Users\\XXXX\\Desktop\\Eclipse_Installer\\GeckoDriver\\chromedriver.exe");
// Create oject of chrome driver 
 WebDriver driver =  new ChromeDriver();
 Thread.sleep(3000);						  driver.get("http://demo.guru99.com/test/simple_context_menu.html");
 driver.manage().window().maximize();
 driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
Actions mouseActn=new Actions(driver);
 WebElement clickContext =driver.findElement(By.xpath("//*[@id=\"authentication\"]/span"));
Thread.sleep(3000);						  mouseActn.contextClick(clickContext).build().perform();
 Thread.sleep(3000);		  
 driver.quit();			  
	}
}

So in this Tutorial we have learned how to double Click and right click in selenium webdriver.

If you guys an comment and topics which can be discussed feel free to contact us and write.

How to perform Drag and Drop Action in Selenium

Previous Topic, In the tutorial we will discuss the How to perform Drag and Drop Action in Selenium . The method that are used under Drag and Drop Action Class in Selenium Webdriver.

How to perform Drag and Drop Action in Selenium?

Drag and Drop Action is basically moving any element from one place and another. Or in other words taking the control of an element from one location and dropping it to another location (releasing the control).

Performing Drag and Drop in Selenium

In selenium webdriver using Action Class, we can perform Drag and Drop operation. The method exposed to drag element and drop to any defined location are as below:

  • dragAndDrop(source, target)
  • dragAndDropBy(source, xOffset, yOffset)

Lets discuss both the methods in Actions class in details

1) dragAndDrop(source, target): This method is called in selenium webdriver once we created the instance variable of Action class, and calling the instance variable followed by (.) . We can call the method. So lets code.

So to under this consider a scenario.

package SeleniumArchitecture;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class FiestTestScriptChrome {
public Boolean Flag =false;
public static void main(String[] args) throws InterruptedException  {
	
//System property of the Chrome driver 
			  System.setProperty("webdriver.chrome.driver","C:\\Users\\XXXXX\\Desktop\\Eclipse_Installer\\GeckoDriver\\chromedriver.exe");
			  
 // Create oject of chrome driver 
 WebDriver driver =  new ChromeDriver();
 Thread.sleep(3000);
driver.get("https://www.seleniumeasy.com/test/drag-and-drop-demo.html");
			 
 driver.manage().window().maximize();
 driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
  try {
WebElement fromLocation =driver.findElement(By.xpath("//div[@id='todrag']//span[1]"));
WebElement toLocation =driver.findElement(By.id("mydropzone"));
							
Actions mouseActn=new Actions(driver);
// Thread.sleep(3000);						mouseActn.dragAndDrop(fromLocation, toLocation).build().perform();
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
				
}
 driver.quit();
}
}

So lets discuss code in details

In the above code after opening the website and maximize the browser, we have created the xpath for element “Draggable 1” by xpath function as WebElement fromLocation =driver.findElement(By.xpath(“//div[@id=’todrag’]//span[1]”));

we have created the xpath for element “Drop here” by id attribute as WebElement toLocation =driver.findElement(By.id(“mydropzone”));

After that we have instanciated the Actions class and passing the driver as parameter as Actions mouseActn=new Actions(driver);

After creating the object of Actions class, we used the instance variable (mouseActn) and click to (.) and called the method (dragAndDrop) along with build().perform().

The reason for calling the build() method and perform method id as below:

  • Build(): This method is called to generate all the actions on a single action.It helps to build the composite method action and perform the action.
  • perform(): This method is used to perform all the actions defined but we initially provide build method get in a single action.

Drag and drop in selenium through co-ordinates

2) dragAndDropBy(source, xOffset, yOffset):Till now we have leaned how to drag and drop in selenium using drapAndDrop() method by passing Webelement , but using this method we drag and drop at the mid of the element at a defined position and trigger the event, but in some of the web page we have to drag and drop the mouse action using the x offset and y offset, these x and y offsets are in pixels.

So in that case we have the to provide the location x offset and y offset as a parameter in dragAndDropBy(source, xOffset, yOffset) method. We have to perform the action the same way as we did earlier, just need to pass extra parameters to the method as below:

Consider xoffset is 40 and y offset is 10, so the code will as

Actions mouseActn=new Actions(driver);
mouseActn.dragAndDropBy(source, 40, 10)

So in the Above tutorial we have covered the Drag and Drop action using selenium and Along with Action Class.

Mouse Hover Action in Selenium

Previous Topic, Mouse Hover Action in Selenium: its basically an action which is performed when user takes the mouse cursor at any of the elements like menu, Tab etc,

it automatically triggers an event and displays multiple sets of other options.

How to perform Mouse Hover Action?

Sometimes it happens that few of the element in web application are not visible in web page,so in that case to perform an action on the particular element.

we have to take the mouse to a particular element and after that the required element gets visible.

So in this tutorial we will discuss the features of Mouse Hover Action in Selenium.

Mouse Hover in Selenium

In selenium webdriver Using Action Class we can move to any of the element visible in web page. The method exposed to take control on mouse hover in selenium is below.

  • moveToElement(Webdriver)
  • moveToElement(target, xOffset, yOffset)

Lets discuss both defined methods in Action class in details.

1) moveToElement(Webdriver): This method can be called in selenium webdriver once we have created the instance variable of Action class, and calling the instance variable followed by (.) ,we can call the method.So lets code.

So to under this consider a scenario.

  • Launch website http://www.airindia.in/ on chrome browser.
  • Maximise your browser.
  • mouse hover to “Manage Your Trip” menu at the top
  • quit the browser
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class FiestTestScriptChrome {
public Boolean Flag =false;
public static void main(String[] args) throws InterruptedException  {
//System property of the Chrome driver 
			  System.setProperty("webdriver.chrome.driver","C:\\Users\\XXXXXXXXX\\Desktop\\Eclipse_Installer\\GeckoDriver\\chromedriver.exe");
			  
 // Create oject of chrome driver 
 WebDriver driver =  new ChromeDriver();
 Thread.sleep(3000);
			  
 driver.get("http://www.airindia.in/");
			 
 driver.manage().window().maximize();
 Thread.sleep(3000);
			  					  
			  
WebElement manageMyTrip =driver.findElement(By.id("aMnu1"));
			   
Actions mouseActn=new Actions(driver);			 			mouseActn.moveToElement(manageMyTrip).build().perform();
			
Thread.sleep(3000);
			  
 driver.quit();
			  
	}

}

So let discuss the code in details.

In the above code after opening the website and maximise the browser, we have created the xpath for element “Manage your Trip” by id attribute as WebElement manageMyTrip =driver.findElement(By.id(“aMnu1”));

After that we have instanciated the Actions class and passing the driver as parameter as Actions mouseActn=new Actions(driver);

After creating the object of Actions class, we used the instance variable (mouseActn) and click to (.) and called the method (moveToMethod) along with build().perform().

The reason for calling the build() method and perform method id as below:

  • Build(): This method is called to generate all the actions on a single action.It helps to build the composite method action and perform the action.
  • perform(): This method is used to perform all the actions defined but we initially provide build method get in a single action.

How to Move To Element in selenium using x,y offset?

2) moveToElement(target, xOffset, yOffset): Till now we have leaned how to mouse hover in selenium using moveToElement() method by passing Webelement , but sometimes using this method we hover mouse at the mid of the element and trigger the event, but in some of the web page we have to hover the mouse action using the x offset and y offset, for ex in Slidder we need to mouse hover till we reach to a defined position.

So in that case we have the to provide the location x offset and y offset as a parameter in oveToElement(target, xOffset, yOffset) method. WE have to perform the action the same way as we did earlier, just need to pass extra parameters to the method as below:

Consider xoffset is 40 and y offset is 10, so the code will as

Actions mouseActn=new Actions(driver);			 			mouseActn.moveToElement(manageMyTrip, 40,10).build().perform()

Webdriver-Browser Commands

Webdriver browser commands are those commands in selenium webdriver from where we can perform any browser operation with defined set of method.

The Method which is called using (.) from reference variable of browser object (can be any chrome,firefox, ie etc) have method with parameter and it return with particular return type or void(no return type).

Lets discuss the Webdriver-Browser commands in details.

1) get command: This method loads a new URL or Webpage on the existing web browser and return void (no return type).The method is displayed void.

Command– driver.get();

Code: driver.get(“http://www.google.com”); String URL = “https://code2test.com”;
driver.get(URL);

2) getTitle(): In Webdriver , the get title retrieves the title of the current web page as it don not accept any parameter and returns a string.

Code: driver. getTitle(“http://www.google.com”);

3) getCurrentUrl(): This method return String, it basically retrives the Url of the current web page treats it as a string .

Code:  String CurrentUrl = driver.getCurrentUrl();

4) getPageSource(): In Webdriver, getPageSource() method helps to extract the sourcecode of your current web page present in browser.

Code: driver. getSourceCode();

5) close():

Object identification through css in selenium

CSS: It stands for “Cascading Style Sheets”, the css is provided in Dom structure for styling, alignment,colouring etc. helps to style a web page. Due to its mechanism it provides a unique approach for object identification in test automation in selenium along with other tools.

Advantage of using Css selector:

  • Faster than xpath
  • most browser support
  • its concise than xpath
  • ease to implement

Let discuss the Css locator in depth.

  1. name Attribute: On Dom structure name attribute is mostly used to represent an element on webpage. In Css name attribute is located using below syntax: css=tagName[name=’value’]

For css locator for the Email text box in facebook page is:

input[name=’email’]

2) class Attribute: In Css dot (.) represents the class attribute.So in Css class attribute represents by the syntax: css=td.attributeValue.

Css locator for the Emai or phone text in facebook page is:

td.html7magic

Note: The Css locator for class locator will not work if the ending tag for an attribute is not available and also will not work if there is space in the text of value of and attribute.

3) id attribute: In Css selector Hash (#) represents the id attribute.The basic syntax for id attribute in Css is-> tagName#attributeValue

Css locator for the Emai or phone text in facebook page is using id is:

input#email

Functions used with Css Locator are below:

1) contains(): “ * ” symbol represents contains function in css locator.This function helps the css locator to locate the element having particular string available in any of attribute value defined.The syntax for contains function is tagName[attributeName*=’attributeValue’]

Css locator for the Emai text Box in facebook page using contains :

input[id*=’em’]

2) starts-with(): The symbol (^) represents starts-with in css locator. Suppose in a Web page we want to locate Email whose type attribute is not static, its dynamic, the start 3 text is always same but the next part is dynamic and changes every time the page gets refresh, so in this case with the help of static string we can locate the element in css locator using starts-with ().The syntax is tagName[attributeName^=’attributeValue’]

Css locator for the password text Box in facebook page starts-with :

input[type^=’pas’]

3) ends-with: The symbol ($) represents ends-with in css locator. Suppose in a Web page we want to locate password text box whose type attribute is not static, its dynamic, the last 3 text is always same but the first part is dynamic and changes every time the page gets refresh, so in this case with the help of static string we can locate the element in css locator using starts-with ().The syntax is tagName[attributeName$=’attributeValue’]

Css locator for the password text Box in facebook page starts-with :

input[type$=’word’]

Object identification for parent child hierarchy using Css locator:

parent immediate child: (>) represents parent immediate child relationship. In similar condition for xpath (/) is used to represent direct or immediate child for ex:

XPATH: html/body/span/input

CSS : html >body> Span > input

Css locator forEmail or phone text in facebook page is below :

form#login_form>table>tbody>tr>td>label