How to handle dropdown in selenium WebDriver?

 Two ways to handle dropdown –

         1.      Using Select class
The big secret to working with drop down is that you don’t want to work with them as WebElements, but instead create a Select element for them. The Select class (java and python documentation) includes utility methods that allow you to perform common tasks. We will be working with the following html:
<select id="id_state" class="form-control" name="id_state" style="">
<option value="">-</option>
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
<option value="6">Colorado</option>
<option value="7">Connecticut</option>
<option value="8">Delaware</option>
In order to deal with dropdown values through selenium WebDriver, Selenium has Select class. (org.openqa.selenium.support.ui.Select;).
We can select value from dropdown, by below simple steps.
Firstly, Identify WebElement with Select tag, that is for your dropdown.
Ex –                  WebElement element = driver.findElement(By.id(” “));
Then, create an object of Select class.
Ex.                     Select s = new Select(listbox);
Then Select the value by one of the applicable methods like ByVisibleText, ByIndex ….whichever can be applied.
    selectByIndex
WebElement element = driver.findElement(By.id("mySelectID")); 
Select s= new Select(element);
s.selectByIndex(0);
    selectByValue
WebElement element = driver.findElement(By.id("mySelectID")); 
Select s= new Select(element);
s.selectByValue("Value");
     selectByVisibleText
WebElement element = driver.findElement(By.id("mySelectID"));
Select s= new Select(element);
s.selectByVisibleText("Option");
           
        2.       Without Using Select class
We can deal with dropdown value without using select class as well. Below are two examples how this can be achieved.


Method 1:

In this example, we find the option via a complex xpath, then click on it:

WebElement myoption = driver.findElement(By.xpath(
    "//Select[@id='mySelectID']/option[normalize-space(text())='Option']")

);
 myOption.click();

Method 2:

In this example, we find all the options, iterate over them, and click the one we want. This is useful if you have some more complex criteria.


WebElement mySelectElm = driver.findElement(By.id("mySelectID")) 
Select mySelect= new Select(mySelect);
List<WebElement> options = mySelect.getOptions();
for (WebElement option : options) {
    if (option.getText().equalsIgnoreCase("Option") {

        option.click();

    }

}

This is all about Selecting dropdown. However, note that, method 1 is more recommended, that is by using Select class.

Refer below post for complete example of Automation of Registration page using Selenium WebDriver.

Refer below video on same –

Hope This Helps !!!!!

How to Automate Registration page using Selenium WebDriver?

In this article, let us talk about how to Automate Registration page. In earlier posts, we saw, how to select value from dropdown, how to select check boxes, how to send value to field etc. Now let us try all in one example. Here is an example of Automation of registration page using Selenium WebDriver.

Refer below post to know how to handle check boxes using selenium WebDriver.
Refer below post to know how to select radio button using selenium WebDriver.
Refer below post to know how to handle dropdown in selenium WebDriver.
URL used for this example:  http://automationpractice.com/index.php
Below code shows the complete code of automate registration page.
package learnAboutActionsClass;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;


public class AutomateRegistrationPage {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  
  //navigate to URL
  driver.navigate().to("http://automationpractice.com/index.php");
  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  driver.findElement(By.xpath("//*[@id='header']/div[2]/div/div/nav/div[1]/a")).click();
  
  driver.findElement(By.xpath("//*[@id='email_create']")).sendKeys("testtest123@gmail.com");
  driver.findElement(By.xpath("//*[@id='SubmitCreate']")).click();
  
  //Select Radio Button
  String valueOfGender = "2"; //in this case, value is integer, it can be String in most of the cases.
  
  List<WebElement> RadioButtonList = driver.findElements(By.name("id_gender"));
  
  System.out.println("Total numer of Radio Buttons for gender field is: " +RadioButtonList.size());
  
  for (int i = 0; i < RadioButtonList.size(); i++){
   String gend = RadioButtonList.get(i).getAttribute("value");
   if (gend.equalsIgnoreCase((valueOfGender))){
    RadioButtonList.get(i).click();
    break;
   }
   
  }
  
  //Enter customer details
  driver.findElement(By.xpath("//*[@id='customer_firstname']")).sendKeys("FirstName");
  driver.findElement(By.xpath("//*[@id='customer_lastname']")).sendKeys("lastName");
  driver.findElement(By.xpath("//*[@id='passwd']")).sendKeys("Password@123");
  
  //Select date of Birth
  Select sDate = new Select(driver.findElement(By.xpath("//*[@id='days']")));
  sDate.selectByVisibleText("2  ");
  
  Select sMonth = new Select(driver.findElement(By.xpath("//*[@id='months']")));
  sMonth.selectByVisibleText("May ");
  
  Select sYear = new Select(driver.findElement(By.xpath("//*[@id='years']")));
  sYear.selectByVisibleText("2015  ");
  
  //select required check boxes
  String newsLetterReq = "Yes";
  if (newsLetterReq.equalsIgnoreCase(newsLetterReq)){
  driver.findElement(By.xpath(".//*[@id='newsletter']")).click();
  }
  
  String reciveSpclOffer = "Yes";
  if (reciveSpclOffer.equalsIgnoreCase(reciveSpclOffer)){
   driver.findElement(By.xpath("//*[@id='optin']")).click();
   
   
  //Fill address related details
  driver.findElement(By.xpath("//*[@id='firstname']")).sendKeys("FnameInAddr");
  driver.findElement(By.xpath("//*[@id='lastname']")).sendKeys("LnameinAddr");
  driver.findElement(By.xpath("//*[@id='company']")).sendKeys("comp");
  driver.findElement(By.xpath("//*[@id='address1']")).sendKeys("addr1");
  driver.findElement(By.xpath("//*[@id='address2']")).sendKeys("addr2");
  driver.findElement(By.xpath("//*[@id='city']")).sendKeys("Pune");
  
  Select sState = new Select(driver.findElement(By.xpath("//*[@id='id_state']")));
  sState.selectByVisibleText("Alabama");
  
  driver.findElement(By.xpath("//*[@id='postcode']")).sendKeys("12345");
  
  Select sCountry = new Select(driver.findElement(By.xpath("//*[@id='id_country']")));
  sCountry.selectByVisibleText("United States");
  
  driver.findElement(By.xpath("//*[@id='other']")).sendKeys("any other info");
  driver.findElement(By.xpath("//*[@id='phone']")).sendKeys("123457876");
  driver.findElement(By.xpath("//*[@id='phone_mobile']")).sendKeys("868768768768");
  driver.findElement(By.xpath("//*[@id='alias']")).sendKeys("alias");
  
  driver.findElement(By.xpath("//*[@id='account-creation_form']")).click();
   
   
  }
  
 }

}

Post your questions / suggestions.

Latest Trends in Software Testing – 2017

Automation testing is among the top in the list of Latest Trends in Software Testing for Year 2017.

Apart from automation testing, there is Agile, DevOPs, Big Data testing, New technologiers like SOA, mobile testing, cloud testing etc. Let us has look on it.
Latest Trends in Software Testing 2017

Automation Testing (Among Top on Latest Trends):

Since last 2 years, Automation testing is growing day by day & all the companies want to automate their applications so as to get testing (might be regression) done fast / reduce cost. Here is the list of trending tools in Automation testing area.
          a.       Selenium WebDriver (Including TestNG, JenkinsCI, Maven etc.)
          b.       BDD testing
          c.       Mobile application testing (tools like Appium)
          d.       Agile Frameworks
          e.       TOSCA
          f.        UFT
          g.       Test Complete

Agile:

It’s a set of methods around iterating and making incremental development with changing (well, evolving) requirements and solutions. Basically, it means being flexible and changing to the needs of the project over it’s life and to listen to the customers.

Advantages of Agile Model:

 The most important of the advantages of agile model is the ability to respond to the changing requirements of the project. This ensures that the efforts of the development team are not wasted, which is often the case with the other methodologies. The changes are integrated immediately, which saves trouble later. There is no guesswork between the development team and the customer, as there is face to face communication and continuous inputs from the client. The documents are to the point, which no leaves no space for ambiguity. The culmination of this is that a high quality software is delivered to the client in the shortest period of time and leaves the customer satisfied.

DevOPs:

DevOPs is a culture, A healthy culture of the organization in which development and operations team to work with each other.
The Process of Development -> Test -> Deploy -> Monitor – > Support should be as smooth as possible.
DevOPs talks about writing test cases before you code, this helps to increase the quality of the product, definatly resulting less bugs.
DevOPs talks about automation, Automation as much as you can.
DevOPs talks about culture in which people should be open minded, transparent, egoless, professional etc..
This was about Latest Trends in Software testing in year 201.
Hope This Helps !!!!

What is actions class in Selenium WebDriver?

Actions class in Selenium WebDriver –

In Webdriver, handling keyboard events and mouse events (including actions such as Drag and Drop or clicking multiple elements With Control key) are done using the advanced user interactions API . It contains Actions and Action classes which are needed when performing these events.

In order to perform action events, we need to use org.openqa.selenium.interactions.Actionsclass.
We need to use perform() to execute the action.
Using Action API, keyboard interactions are simple to do with webdriver. In Advanced User Interactions API, interaction with element is possible either by clicking on element or sending a Keys using sendKeys()
To use mouse actions, we need to use current location of the element and then perform the action.
The following are the regularly used mouse and keyboard events:
Method :clickAndHold()
Purpose: Clicks without releasing the current mouse location

Method : contextClick()
Purpose: Performs a context-click at the current mouse location (double click).

Method: doubleClick()
Purpose: Performs a double click at the current mouse location

Method: dragAndDrop(source,target)
Parameters: Source and Target
Purpose: Performs click and hold at the location of the source element and moves to the location of the target element then releases the mouse.

Method : dragAndDropBy(source,x-offset,y-offset)
Parameters: Source, xOffset – horizontal move, y-Offset – vertical move Offset
Purpose: Performs click and hold at the location of the source element moves by a given off set, then releases the mouse.

Method: keyDown(modifier_key)
Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONROL)
Purpose: Performs a modifier key press, doesn’t release the modifier key. Subsequent interactions may assume it’s kept pressed

Method: keyUp(modifier_key)
Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONROL)
Purpose: Performs a key release.

Method: moveByOffset(x-offset, y-offset)
Parameters: X-Offset , Horizontal offset, a negative value means moving the mouse to left side.
Y-Offset, vertical offset, a negative value means moving the mouse to up.
Purpose: Moves the mouse position from its current position by the given offset.

Method: moveToElement(toElement)
Parameters: toElement – Element to Move to
Purpose: It moves the Mouse to the middle of the element.

Method: release()
Purpose: It releases the left mouse button at the current mouse location.

Method: sendKeys(onElement, charSequence)
Parameters: onElement, which will receive the keyStrokes, usually text field.
charsequence- any string value representing the sequence of keyStrokes to be sent.
Purpose: It sends a series of keyStrokes onto the element

As mentioned above, we can use Actions class for following actions –

Hope This helps !!!

MouseHover action in selenium WebDriver

Mousehover action in selenium WebDriver –

In the Actions class, the user, can perform one action, by simply calling it into the driver instance, followed by the method perform().

MouseHover using Actions Class in Selenium WebDriver

Let us see about mousehover action in selenium. If the menu bar or anywhere on the page, the menu has dropdown, and the dropdown options appear only when you hover the mouse on that menu.

So, in this case, we can use mouse hover action of the Actions class in selenium

Let us see, hot this can be achieved.

In my blog (URL: http://automationtalks.com/), suppose you want to select the sub-menu (Selenium WebDriver) of Menu: Selenium.

See below screen.
MouseHover using Actions Class in Selenium WebDriver
To Achieve this, follow below mentioned steps.
  1. Open the browser.
2.    Navigate to the given URL (http://automationtalks.com/).
  1. Mouse Hover on “Selenium Tutorial” tab present in the top navigational bar.
  2. Select the Menu which you want to click on (let us consider here as – “Selenium WebDriver”.
  3. Click on the “Selenium WebDriver”.
  4. Close the browser.
First define actions class –

                        Actions act = new Actions(driver);

Then, mousehover using actions class, syntax below –

act.moveToElement(driver.findElement(“webelement_Menu_location”)).build().perform();

Now, the submenu should be visible, Then click on the submenu –

driver.findElement(“WebElement_submenu”).click();

Below is the example how can be mouse hover achieved in selenium WebDriver.

package demoPackage1;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;

public class ActionsClass {
  
  @Test
  public void TestCase() throws InterruptedException{
    
    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    
    driver.navigate().to("http://automationtalks.com/");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    
    Actions act = new Actions(driver);

    //Define actions class & move to webelement  (Hove mouse to webelement)
    act.moveToElement(driver.findElement(By.xpath("//span[contains(.,'Selenium Tutorial')]"))).build().perform();
    
    //After mouse hover, element form dropdown is appeared, then click on it.
    driver.findElement(By.xpath("//a[contains(.,'Selenium WebDriver')]")).click();
    
    Thread.sleep(3000);
    
    
    driver.close();
    driver.quit();
    
    

    
  }

}

Hope This Helps !!!!

Right Click (Context Click) in Selenium

Right click or Context click in selenium WebDriver using Actions class-

Sometimes you’ll run into an app that has functionality hidden behind a right-click menu (a.k.a. a context menu). These menus tend to be system level menus that are untouchable by Selenium. So how do you test this functionality?

Right Click (Context Click ) using Actions Class using Selenium WebDriver
We can then select an option from the menu by traversing it with keyboard arrow keys (which we can issue with the Action Builder’s send_keys command).
In Selenium WebDriver to perform right click on any web element is not a complex process. All you have to do is create an instance of Action class and call the methods defined in it to perform the actions you want. Follow the below steps in order to perform right click on any web element:

Below are the Steps we have followed in the example:

    Identify the element
    Wait for the presence of Element
    Now perform Context click
    After that we need to select the required link.

Example –

package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class RightClickInSelenium {
 
 public static void main(String[] args){
  
  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://automationtalks.com/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  Actions act = new Actions(driver);
  act.moveToElement(driver.findElement(By.xpath("//*[@id='mbtnav']/li[3]/a"))).build().perform();
   act.contextClick(driver.findElement(By.xpath("//*[@id='mbtnav']/li[3]/ul/li[2]/a"))).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
  //Switching between tabs using CTRL + tab keys.
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
    //Switch to current selected tab's content.
    driver.switchTo().defaultContent();  
 }

}

Here the method sendKeys(Keys.ARROW_DOWN) is used to select an option from the list. If you will not add this method, the right click on the web element will be performed and the option list which appears after the right click will get disappeared without selecting any option.

We can perform the right click on any web element using the Robot class too. Here you first need to move the mouse to the particular web element and then perform the required action…!!!

Actions class in Selenium WebDrivr

Perform series of actions using Actions class in selenium WebDriver?

You can build a perform series of actions using the Action and Actions classes. Just remember to close the series with the build() method. Consider the sample code below.

Perform Series of Actions Using Actions class in selenium WebDriver
package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class PerformSeriesOfActions {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  WebDriver driver = new FirefoxDriver();
  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  driver.navigate().to("https://www.facebook.com/");
  
  WebElement element = driver.findElement(By.xpath("//*[@id='email']"));
  
  Actions act = new Actions(driver);
  //Below line sends some text to field by converting it to uppercase, then double click the text so that it will select all, then do right click
  act.moveToElement(element).click().keyDown(element, Keys.SHIFT).sendKeys("panarkhede").keyUp(element, Keys.SHIFT).doubleClick(element).contextClick(element).build().perform();
  driver.quit();
 }

}
Observe below screen shot to see the series of actions performed by using above code –
Firstly, Clicked on text box.
then, sent text to text box by converting it to upper case.
then double clicked on the entered test, so that text is selected.
then right clicked on the text.

Hope This Helps !!!

How to use tab key (button) in selenium WebDriver?

There are multiple ways to perform Tab key functionality. Using Actions Class, Using SendKeys() method & few other. Let us talk about them one by one.

TAB Key using Actions Class in Selenium WebDriver

1. Using function sendKeys(Keys.Tab).

    WebElement inputField = driver.findElement(By.Locator("LocatorValue"));
    inputField.sendKeys(Keys.TAB);

2. If you are using Java then you can use Java ROBOT class to perform keyboard actions.

Robot robot = new Robot();
// Simulate key Events
robot.keyPress(keyEvent.VK_TAB);
robot.keyRelease(keyEvent.VK_TAB);

3. You can use Ascii value in send key function like sendKeys(//0061); I am not sure the ASCII value of Tag it’s just an example.

4. Using Actions class. –

Basically, you need to have instance of Actions class and then call sendKeys with TAB as TAB key.
package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class TabKeyUsingActionsClass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
WebDriver driver = new FirefoxDriver();
  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  driver.navigate().to("http://automationtalks.com/");
  
  WebElement element = driver.findElement(By.xpath("//input[@class='search']"));
  element.sendKeys("text to be searched");
   
   Actions act = new Actions(driver);
   
   act.sendKeys(Keys.TAB).build().perform();
   act.sendKeys(Keys.RETURN).build().perform();
   
 }

}

Hope This Helps !!!!

How to send text in capital letters into a text-box using Actions class in Selenium WebDriver?

We can send the text in capital letters (Upper case) in to a text box by using actions class of the selenium. Very simple.  First press the SHIFT key and then send the text which you want to convert to capital letter before sending to text box.
Send Capital letters to textbox using actions class in Selenium WebDriver
Below program illustrates the same –
package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class SendTextInCapitalLetter {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  WebDriver driver = new FirefoxDriver();

  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();

  driver.navigate().to("http://automationtalks.com");

  String TextToBeConvertAndSendInUpperCase = "Synchronization in Selenium";

  WebElement element = driver.findElement(By.xpath("//input[@class='search']"));

  Actions act = new Actions(driver);

  act.keyDown(element, Keys.SHIFT).sendKeys(TextToBeConvertAndSendInUpperCase).keyDown(element, Keys.SHIFT).build().perform();

 }

}
Original Text was:  “Synchronization in Selenium”;
The text sent to the text box –
Hope this helps !!! post your questions if any.

How to refresh webpage using Action class in selenium WebDriver?

Refresh webpage using Actions Class in Selenium WebDriver –
There are various ways to refresh webpage in selenium webdriver. One of them using Actions class.
Refresh WebPage using Actions class in Selenium WebDriver
Application can be refreshed in multiple ways. We can use

driver.navigate().refresh();
Method, or can send key F5.
Here, Web Page refresh can be achieved by using Actions class of the selenium WebDriver.
Below program explain this –
package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class RefreshUsingActionsClass {

 public static void main(String[] args) throws InterruptedException {
  // TODO Auto-generated method stub
  
  WebDriver driver = new FirefoxDriver();
  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");
  
  //sleep the website for 4 seconds so that we can notice the refresh of web page
  Thread.sleep(4000);
  
  Actions act = new Actions(driver);
  
  //using below command we can refresh the webpage
  act.keyDown(Keys.CONTROL).sendKeys(Keys.F5).build().perform();
 }

}