Handling Dynamic Elements in Selenium WebDriver


                      Handling Dynamic Elements in Selenium WebDriver

Dynamic elements are those elements which have identifiers that are dynamically generated. Dynamic identifiers are normally used for buttons, text-fields and buttons. Let us take an example of a button whose ID is in following format…
In this test scenario, we can observe that element ID is not static. There is a number combined with text that auto increments on user action. So, we can expect that on every script execution there will be a new ID for the element.
There are multiple approaches which can be used to handle dynamic elements but there is no definite one. An approach might work in one scenario and might not work in another. It all depends on the code, element type, locator and test script requirements.
1. Absolute XPath
Xpath Position or Absolute Xpath are most frequently used to resolve the dynamic element issues. Only problem with using XPath locators is that they are very fragile. They are most prone to breakage in case of change in web page. This factor could get worse exponentially as the test suite size and complexity increases. Below is an example of Absolute XPath and XPath Position
2. Identify Element by starting Text
If the dynamic elements have a definite pattern to them, then we can also use JavaScript functions like “starts-with” or “contains” in our element locators to separate the dynamic part of locator from static part.
For example, in case of dynamic submit button Id example which we discussed earlier, we can apply ‘starts-with’ function to access this locator irrespective of its dynamic part.
3. Identify Element by containing Text
Similarly, in some scenarios where dynamic element is surrounded by a static value, we can use ‘contains’ function. For example we have following element locators…
As we can see ‘usefield’ part of element is static, so we can apply ‘contains’ function to access this element locator as shown below…
4. Identify Element by Index
If there are multiple elements present on page with same locator then we can use following Java code in our selenium WebDriver script to interact with element of particular index.
5. Identify Element with reference of a closest stable element
We can use the DOM structure to find the closest stable element first and then this stable element can be used as a reference element to find the required element.
DOM structure could be found using Firefox extension like Firebug and FirePath. But in complex and large applications this approach is difficult to use because of large DOM structure.
6. Identify Element by stable preceding Text
For web elements like text field and text areas we can identify them by using the stable text labels nearby. This approach might not be possible in all scenarios but it does resolve the dynamic element issues where possible. Example of this approach is shown below.

How to Run the Script in the Chrome Browser


                                    How to Run the Script in the Chrome Browser

      1. Create new Java Project
                [Name of the project is "FFTesting"             
      2. Create a new Java class file under the Package
                [Give a name of the class is "Runtesting.java"
      3. Download ChromeDriver server
           First of all, download latest version of ChromeDriver server for webdriver software                        testing tool. from https://sites.google.com/a/chromium.org/chromedriver/downloads

            Download the file and extract in the folder. You get "chromedriver.exe"
    
      4. Next add the selenium server Jar files to the Project. Download Selenium Server
                [Right click on the Project Name, Mouse over on Build Path and select 'Configure Build Path',                  Select Libraries tab, Click on Add External Jars and select the selenium server jar from your                   local machine]
       5. .Write the script in the Java and execute it.
            Please find the below example program to open Google in chrome browser
              System.setProperty("webdriver.chrome.driver","path of that chromedriver.exe file");


import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class Runtesting{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver","path of that chromedriver.exe file");
      WebDriver driver = new ChromeDriver();
   
      //Launch website
      driver.navigate().to("http://google.com/");
      
      //Maximize the browser
      driver.manage().window().maximize();
      
      //Close the Browser.
      driver.close();
   }
}
               

How to Run the Script in the Firefox Browser


                                    How to Run the Script in the Firefox Browser

      1. Create new Java Project
                [Name of the project is "FFTesting"             
      2. Create a new Java class file under the Package
                [Give a name of the class is "Runtesting.java"
       3. Next add the selenium server Jar files to the Project. Download Selenium Server
                [Right click on the Project Name, Mouse over on Build Path and select 'Configure Build Path',                  Select Libraries tab, Click on Add External Jars and select the selenium server jar from your                   local machine]
       4. .Write the script in the Java and execute it.
            Please find the below example program to open Google in Firefox browser
              
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Runtesting{
   public static void main(String[] args) {
   
      WebDriver driver = new FirefoxDriver();
   
      //Launch website
      driver.navigate().to("http://google.com/");
      
      //Maximize the browser
      driver.manage().window().maximize();
      
      //Close the Browser.
      driver.close();
   }
}
               

Selenium:Environment Setup

In order to develop Selenium RC or WebDriver scripts, users have to ensure that they have the initial configuration done. Setting up the environment involves the following steps.
  • Download and Install Java
  • Download and Configure Eclipse
  • Configure FireBug and FirePath
  • Configure Selenium RC
  • Configure Selenium WebDriver

Download and Install Java

We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Let us see how to download and install Java.
Step 1 : Navigate to the URL:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step 2 : Go to "Downloads" section and select "JDK Download".
Selenium IDE 30
Step 3 : Select "Accept License Agreement" radio button.
Selenium IDE 31
Step 4 : Select the appropriate installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk.
Selenium IDE 32
Step 5 : Run the downloaded exe file to launch the Installer wizard. Click 'Next' to continue.
Selenium IDE 33
Step 6 : Select the features and click 'Next'.
Selenium IDE 34
Step 7 : The installer is extracted and its progress is shown in the wizard.
Selenium IDE 35
Step 8 : The user can choose the install location and click 'Next'.
Selenium IDE 36
Step 9 : The installer installs the JDK and new files are copied across.
Selenium IDE 37
Step 10 : The Installer installs successfully and displays the same to the user.
Selenium IDE 38
Step 11 : To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an "unknown command" error.
Selenium IDE 48

Download and Configure Eclipse

Step 1 : Navigate to the URL: http://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture.
Selenium IDE 39
Step 2 : Click the 'Download' button.
Selenium IDE 40
Step 3 : The download would be in a Zipped format. Unzip the contents.
Selenium IDE 41
Step 4 : Locate Eclipse.exe and double click on the file.
Selenium IDE 42
Step 5 : To configure the workspace, select the location where the development has to take place.
Selenium IDE 43
Step 6 : The Eclipse window opens as shown below.
Selenium IDE 44

Configure FireBug and FirePath

To work with Selenium RC or WebDriver, we need to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins.
Step 1 : Navigate to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin.
Selenium IDE 62
Step 2 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Selenium IDE 63
Step 3 : After installing, we can launch the plugin by navigating to "Web Developer" >> "Firebug".
Selenium IDE 64
Step 4 : FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to "https://addons.mozilla.org/en-US/firefox/addon/firepath/"
Selenium IDE 65
Step 5 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Selenium IDE 66
Step 6 : Now launch "Firebug" by navigating to "Tools" >> "Webdeveloper" >> "Firebug".
Selenium IDE 67

Example

Now let us understand how to use FireBug and FirePath with an example. For demonstration, we will use www.google.com and capture the properties of the text box of "google.com".
Step 1 : First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact.
Selenium IDE 68
Step 2 : To fetch the XPath of the object, go to 'firepath' tab and perform the following steps.
  • Click the Spy icon.
  • Select the Control for which we would like to capture the XPath
  • XPath of the selected control would be generated.
Selenium IDE 69

Configure Selenium RC

Now let us look at how to configure Selenium Remote control. We will understand how to develop scripts with Selenium RC in later chapters, however for now, we will understand just the configuration part of it.
Step 1 : Navigate to the Selenium downloads section http://www.seleniumhq.org/download/ and download Selenium Server by clicking on its version number as shown below.
Selenium IDE 45
Step 2 : After downloading, we need to start the Selenium Server. To do so, open command prompt and navigate to the folder where the downloaded JAR file is kept as shown below.
Selenium IDE 46
Step 3 : To start the server, use the command 'java -jar <<downloaded jar name >> and if java JDK is installed properly, you would get a success message as shown below. Now we can start writing Selenium RC scripts.
Selenium IDE 47

Configure Selenium WebDriver

Now let us look at how to configure Selenium WebDriver. We will understand how to develop scripts with Selenium WebDriver in later chapters, however for now, we will understand just the configuration part of it.
Step 1 : Navigate to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below.
Selenium IDE 49
Step 2 : The downloaded file is in Zipped format and one has to unzip the contents to map it to the project folder.
Selenium IDE 49
Step 3 : The Unzipped contents would be displayed as shown below. How to map it to the project folder and how to start scripting would be dealt in the webDriver chapter.
Selenium IDE 51

Selenium Introduction


                                                 Selenium

Selenium is an open-source and a portable automated software testing tool for testing web applications. It has capabilities to operate across different browsers and operating systems. Selenium is not just a single tool but a set of tools that helps testers to automate web-based applications more efficiently.
Let us now understand each one of the tools available in the Selenium suite and their usage.
ToolDescription
Selenium IDESelenium Integrated Development Environment (IDE) is a Firefox plugin that lets testers to record their actions as they follow the workflow that they need to test.
Selenium RCSelenium Remote Control (RC) was the flagship testing framework that allowed more than simple browser actions and linear execution. It makes use of the full power of programming languages such as Java, C#, PHP, Python, Ruby and PERL to create more complex tests.
Selenium WebDriverSelenium WebDriver is the successor to Selenium RC which sends commands directly to the browser and retrieves results.
Selenium GridSelenium Grid is a tool used to run parallel tests across different machines and different browsers simultaneously which results in minimized execution time.

Advantages of Selenium

QTP and Selenium are the most used tools in the market for software automation testing. Hence it makes sense to compare the pros of Selenium over QTP.
SeleniumQTP
Selenium is an open-source tool.QTP is a commercial tool and there is a cost involved in each one of the licenses.
Can be extended for various technologies that expose DOM.Limited add-ons and needs add-ons for each one of the technologies.
Has capabilities to execute scripts across different browsers.Can run tests in specific versions of Firefox , IE, and Chrome.
Can execute scripts on various operating systems.Works only with Windows.
Supports mobile devices.Supports mobile devices with the help of third-party tools.
Executes tests within the browser, so focus is NOT required while script execution is in progress.Needs Focus during script execution, as the tool acts on the browser (mimics user actions).
Can execute tests in parallel with the use of Selenium Grids.QTP cannot execute tests in parallel, however integrating QTP with QC allows testers to execute in parallel. QC is also a commercial tool.

Disadvantages of Selenium

Let us now discuss the pitfalls of Selenium over QTP.
SeleniumQTP
Supports only web based applications.Can test both web and desktop applications.
No feature such as Object Repository/Recovery ScenarioQTP has built-in object repositories and recovery scenarios.
No IDE, so the script development won't be as fast as QTP.More intuitive IDE; automation can be achieved faster.
Cannot access controls within the browser.Can access controls within the browser such as favorites bar, backward, and forward buttons.
No default test report generation.Default test result generation within the tool.
For parameterization, users has to rely on the programming language.Parameterization is built-in and easy to implement.

Handling Dynamic Elements in Selenium WebDriver

                       Handling Dynamic Elements in Selenium WebDriver Dynamic elements are those elements which have identifiers that a...