Most Popular Selenium WebDriver Commands as Reusable Functions.

In general we search for Most Popular Selenium WebDriver Commands and ready made function in our day today life and but finding such article is really very tought to get, Since Selenium WebDriver is like a magic wand to automation tester to test the web application. Selenium WebDrive has not only  made automation more Object oriented through it OOPs API  but it has also solve the  the most complaining performance of browser launching in Selenium 1.0 and the most important thing that has given a panacea to automation engineers’ hand, is its ability to handle Single Host origin policy

Selenium WebDriver has left more impact on functional test coverage . So for proficiency this post is going to be one of your favorite one. Because these functions written for Selenium Commands can be easily copy and past in your code without giving much thought of it.

For using these function, first create any of the class where you want to add all the custom function for most of the selenium commands which we usually use in our day to day script in Selenium WebDriver.

Selenium WebDriver Commands

Today I am going to post most popular selenium webdriver commands to make your journey with selenium commands and functional testing easy.

1- IsElementPresent/Text Present  function in Selenium WebDriver : 

In general , we found issues related to element not found in failed cases in general. So here we have three ways to identify element on page.

This selenium command/ method is going to give you one reusable function to use for elemenet on screen.

Finding elements by using function that take argument of By class

private boolean isElementPresent(WebDriver driver, By by)
try{
driver.findElement(by);
return true;
}
catch(Exception e)
{
return false;
}
}

Using the size to decide whether element is there or not

if(driver.findElements(Locator).size()>0
{
return true
}else
{
return false
}
}

Finding the text using the PageSource
driver.PageSource.Contains("TEXT that you want to see on the page");

For more detail read : Handling Element Not Found Exception In Selenium WebDriver

2- Finding WebElement  by using various locators in WebDriver

In this we have listed all the locator methods available in Selenium WebDriver, which can be used to identify any of the element on webpage.

Using ID  WebElement welement = driver.findElement(By.id(“Id from webpage”)); // by using id

Using Name  WebElement welement = driver.findElement(By.name(“Name of WebElement”)); //by using name

Using Tag Name  WebElement welement = driver.findElement(By.tagName(“tag name”)); // by using tag

Using Xpath  WebElement welement = driver.findElement(By.xpath(“xpath of  webElement”)); //

Using CSS  WebElement welement = driver.findElement(By.CSS(“CSS locator path”));

Using LinkText  WebElement welement = driver.findElement(By.LinkText(“LinkText”));
Read these articles:
XPath in Selenium

3- Working With Pop-ups In Selenium WebDriver:

This function will fetch message on Pop-up

public static String getPopupMessage(final WebDriver driver) {
String message = null;
try {
Alert alert = driver.switchTo().alert();
message = alert.getText();
alert.accept();
} catch (Exception e) {
message = null;
}
System.out.println("message"+message);
return message;
}

This function will Canceling pop-up in Selenium-WebDriver


public static String cancelPopupMessageBox(final WebDriver driver) {
String message = null;
try {
Alert alert = driver.switchTo().alert();
message = alert.getText();
alert.dismiss();
} catch (Exception e) {
message = null;
}
return message;
}

Inserting string in Text Field in Selenium-WebDriver


public static void insertText(WebDriver driver, By locator, String value) {
WebElement field = driver.findElement(locator);
field.clear();
field.sendKeys(value);
}

4- Reading ToolTip text in in Selenium-WebDriver

In this
public static String tooltipText(WebDriver driver, By locator){
String tooltip = driver.findElement(locator).getAttribute("title");
return tooltip;
}

5- Selecting Radio Button in Selenium-WebDriver



public static void selectRadioButton(WebDriver driver, By locator, String value){ List select = driver.findElements(locator);
for (WebElement element : select)
{
if (element.getAttribute("value").equalsIgnoreCase(value)){
element.click();
}
}

6- Selecting CheckBox in Selenium-WebDriver



public static void selectCheckboxes(WebDriver driver, By locator,String value)
{
List abc = driver.findElements(locator);
List list = new ArrayListArrays.asList(value.split(",")));
for (String check : list){
for (WebElement chk : abc){
if(chk.getAttribute("value").equalsIgnoreCase(check)){
chk.click();
}}}}

7- Selecting Dropdown in Selenium-WebDriver


public static void selectDropdown(WebDriver driver, By locator, String value){
new Select (driver.findElement(locator)).selectByVisibleText(value); }

8- Selecting searched dropdown in Selenium-WebDriver


public static void selectSearchDropdown(WebDriver driver, By locator, String value){
driver.findElement(locator).click();
driver.findElement(locator).sendKeys(value);
driver.findElement(locator).sendKeys(Keys.TAB);
}

9- Uploading file using  Selenium-WebDriver


public static void uploadFile(WebDriver driver, By locator, String path){
driver.findElement(locator).sendKeys(path);
}

10- Downloading file in Selenium-WebDriver


Here we will click on a link and will download the file with a predefined name at some specified location.
public static void downloadFile(String href, String fileName) throws Exception{
URL url = null;
URLConnection con = null;
int i;
url = new URL(href);
con = url.openConnection();
// Here we are specifying the location where we really want to save the file.
File file = new File(".//OutputData//" + fileName);
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
}

11- Handling multiple Pop ups 


read  Handling Multiple Windows in WebDriver

12- Wait() in Selenium-WebDriver

  1. Implicit Wait :
    driver.manage.timeouts().implicitlyWait(10,TimeUnit.SECONDS);
  2. Explicit Wait:WebDriverWait wait = new WebDriverWait(driver,10);
    wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/name("locator"));
  3.  Using Sleep method of java
    Thread.sleep(time in milisecond)

13- Navigation method of Selenium WebDriver Interface 

  • to() method (its a alternative of get() method)
    driver.navigate().to(Url);
    This will open the URL that you have inserted as argument
  • back() – use to navigate one step back from current position in recent history syntax == driver.navigate().back();
  • forward() – use to navigate one step forward in browser history driver.navigate().forward();
  • refresh() – This will refresh you current open url driver.navigate().refresh();

14- Deleting all Cookies before doing any kind of action  


driver.manage().deleteAllCookies();
This will delete all cookies

15- Pressing any Keyboard key using Action builder class of Selenium WebDriver


WebDriver has rewarded us with one class Action to handle all keyboard and Mouse action. While creating a action builder its constructor takes WebDriver as argument. Here I am taking example of pressing Control key
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL).click(someElement).click(someOtherElement).keyUp(Keys.CONTROL).build().perform();


When we press multiple keys or action together then we need to bind all in a single command by using build() method and perform() method intend us to perform the action.
In the same way you can handle other key actions.

16- Drag and Drop action in Selenium Webdriver


In this we need to specify both WebElement  like Source and target and for draganddrop Action class has a method with two argument so let see how it normally look like
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();

17- Handling iFrame In Selenium WebDriver

Iframe is one element on webpage which are one independent pages inside a web page and some time it creates issue to any of the new Selenium Learners. Due to its present user first needs to switch inside this iframe. Only after this, user can perform action on any of the element present on the independent website which is inside iframe.

So here are the functions which you can directly use in your utlity class or selenium base class.

public void selectIFrameUsingIndex(WebDriver driver, int index) {

//Selecting index
public void selectIFrameUsingIndex(WebDriver driver, int index) {   
 
    driver.switchTo().frame(index);
}

//Using iframe name
public void selectIFrameUsingIndex(WebDriver driver, String name) {

    driver.switchTo().frame(name);
}

//Using WebElement 
public void selectIFrameUsingIndex(WebDriver driver, WebElement element) {

    driver.switchTo().frame(element);
}

Reference site
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/

Dwarika Dhish Mishra

My name is Dwarika Dhish Mishra, its just my name and I am trying to bring the worth of my name in to actions and wants to be the solution not the problem. I believe in spreading knowledge and happiness. More over I am fun loving person and like travelling a lot. By nature I am a tester and a solution maker. I believe in the tag line of http://ted.org “Idea worth spreading” . For the same, I have created this blog to bring more and more learning to tester fraternity through day to day learning in professional and personal life. All contents are the part of my learning and so are available for all..So please spread the contents as much as you can at your end so that it could reach to every needful people in testing fraternity. I am pretty happy that more and more people are showing interest to become the part your Abode QA blog and I think this is good sign for us all because more and more content would be before you to read and to cherish. You may write or call me at my Email id: dwarika1987@gmail.com Cell: 9999978609

You may also like...

18 Responses

  1. Awesome…many IMP commands gathered at one place. Thanks!!!

  2. dhanraj says:

    Great !!!!

    keep it up

  3. shiv says:

    useful than expected..Thanks a lot.

  4. Rajani says:

    Very Important for selenium beginners. Thanks..

  5. Mohan says:

    Awesome collection…thanks dude

  6. Prakash says:

    It is helpful.

  7. ravi says:

    Very helpful. Thanks for having all IMP ones at one place.

  8. Basha Panyam says:

    This commands are very helpful to us thank u somuchhhhhhhh

  9. Basha Panyam says:

    HOW TO GENERATE A BUG REPORT AND HOW TO SEND TO THE DEVELPOER

  10. Raju says:

    Very Help full commands

  11. ramkumar says:

    awesome information buddy 🙂 learnt a lot and its good for preparing for interviews too

  12. Reza Haque says:

    It’s really helpful. It could be more helpful if you do something for interview preparation like framework overview, question and answer……….

  13. Gopika says:

    Great lists of commands and really it will be more useful for both freshers and working professionals. I would like to visit your blog often and I will share to my friends. Keep rocking!!

    • @Gopika
      Nice to see you like the blog. But please don’t spam…Although it is good that you are trying to train people but there are lot of ways to do that..

      Anyways hope to see more views from you in future.

  14. Maz says:

    Nice post very useful for students/professionals. As by reading this post them will learn many things about selenium Training.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.