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.

commands

1. Creating New Instance Of Firefox Driver
WebDriver driver = new FirefoxDriver();
Above given syntax will create new instance of Firefox driver.


2. Command To Open URL In Browser
driver.get("http://only-testing-blog.blogspot.com/2013/11/new-test.html");
This syntax will open specified URL of software web application in web browser. 

3. Clicking on any element or button of webpage
driver.findElement(By.id("submitButton")).click();
Above given syntax will click on targeted element in webdriver.


4. Store text of targeted element in variable
String dropdown = driver.findElement(By.tagName("select")).getText();
This syntax will retrieve text from targeted element of software web application page and will store it in variable = dropdown.

5. Typing text in text box or text area.
driver.findElement(By.name("fname")).sendKeys("My First Name");
Above syntax will type specified text in targeted element. 

6. Applying Implicit wait in webdriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
This syntax will force webdriver to wait for 15 second if element not found on page of software web application. 

7. Applying Explicit wait in webdriver with WebDriver canned conditions.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id='timeLeft']"), "Time left: 7 seconds"));
Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7 seconds" to be appear on targeted element.

8. Get page title in selenium webdriver
driver.getTitle();
It will retrieve page title and you can store it in variable to use in next steps.

9. Get Current Page URL In Selenium WebDriver
driver.getCurrentUrl();
It will retrieve current page URL and you can use it to compare with your expected URL.

10. Get domain name using java script executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return document.domain");
Above syntax will retrieve your software application's domain name using webdriver's java script executor interface and store it in to variable.

11. Generate alert using webdriver's java script executor interface
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
It will generate alert during your selenium webdriver test case execution.

12. Selecting or Deselecting value from drop down in selenium webdriver.
  • Select By Visible Text
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
It will select value from drop down list using visible text value = "Audi".
  • Select By Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
It will select value by value = "Italy".
  • Select By Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
It will select value by index= 0(First option).



  • Deselect by Visible Text
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");
It will deselect option by visible text = Russia from list box.
  • Deselect by Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");
It will deselect option by value = Mexico from list box.
  • Deselect by Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
It will deselect option by Index = 5 from list box.
  • Deselect All
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
It will remove all selections from list box of software application's page.


  • isMultiple()
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
It will return true if select box is multiselect else it will return false.


13. Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testing-blog.blogspot.com/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step back and 3rd command will navigate one step forward. 

14. Verify Element Present in Selenium WebDriver
Boolean iselementpresent = driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in variable iselementpresent.

15. Capturing entire page screenshot in Selenium WebDriver
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
It will capture page screenshot and store it in your D: drive. 
16. Generating Mouse Hover Event In WebDriver
Actions actions = new Actions(driver);
WebElement moveonmenu = driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();
Above example will move mouse on targeted element.


17. Handling Multiple Windows In Selenium WebDriver.
  1. Get All Window Handles.
  2. Set<String> AllWindowHandles = driver.getWindowHandles();
  3. Extract parent and child window handle from all window handles.
  4. String window1 = (String) AllWindowHandles.toArray()[0];
    String window2 = (String) AllWindowHandles.toArray()[1];
  5. Use window handle to switch from one window to other window.
  6. driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to switch from one window to another window.

18. Check Whether Element is Enabled Or Disabled In Selenium Web driver.
boolean fname = driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not. You can use it for any input element.
19. Enable/Disable Textbox During Selenium Webdriver Test Case Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname')[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
It will disable fname element using setAttribute() method and enable lname element using removeAttribute() method. 

20. Selenium WebDriver Assertions With TestNG Framework
  • assertEquals
Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal values. 
  • assertNotEquals
Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values. 
  • assertTrue
Assert.assertTrue(condition);
assertTrue assertion works for boolean value true assertion. 
Assert.assertFalse(condition);
assertFalse assertion works for boolean value false assertion. 

21. Submit() method to submit form
driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form.

22. Handling Alert, Confirmation and Prompts Popups

String myalert = driver.switchTo().alert().getText();
To store alert text. 
driver.switchTo().alert().accept();
To accept alert. 

driver.switchTo().alert().dismiss();
To dismiss confirmation. 
driver.switchTo().alert().sendKeys("This Is John");
To type text In text box of prompt popup. - See more at: http://software-testing-tutorials-automation.blogspot.in/2014/01/selenium-webdriver-tutorials-basic.html#sthash.WJjWUsrZ.dpuf

selenium code

Script Creation

For script creation, we would be using “Learning_Selenium” project created in the previous tutorial and “gmail.com” as the application under test (AUT).
Scenario:
  • Launch the browser and open “Gmail.com”.
  • Verify the title of the page and print the verification result.
  • Enter the username and Password.
  • Click on the Sign in button.
  • Close the web browser.
Step 1: Create a new java class named as “Gmail_Login” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “Gmail_Login.java” class.
1import org.openqa.selenium.By;
2import org.openqa.selenium.WebDriver;
3import org.openqa.selenium.WebElement;
4import org.openqa.selenium.firefox.FirefoxDriver;
5 
6public class Gmail_Login {
7/**
8* @param args
9*/
10       public static void main(String[] args) {
11              
12// objects and variables instantiation
13              WebDriver driver = new FirefoxDriver();
14              String appUrl ="https://accounts.google.com";
15              
16// launch the firefox browser and open the application url
17              driver.get(appUrl);
18              
19// maximize the browser window
20              driver.manage().window().maximize();
21              
22// declare and initialize the variable to store the expected title of the webpage.
23              String expectedTitle = " Sign in - Google Accounts ";
24              
25// fetch the title of the web page and save it into a string variable
26              String actualTitle = driver.getTitle();
27              
28// compare the expected title of the page with the actual title of the page and print the result
29              if (expectedTitle.equals(actualTitle))
30              {
31                     System.out.println("Verification Successful - The correct title is displayed on the web page.");
32              }
33             else
34              {
35                     System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
36              }
37 
38// enter a valid username in the email textbox
39              WebElement username = driver.findElement(By.id("Email"));
40              username.clear();
41              username.sendKeys("TestSelenium");
42              
43// enter a valid password in the password textbox
44              WebElement password = driver.findElement(By.id("Passwd"));
45              password.clear();
46              password.sendKeys("password123");
47              
48// click on the Sign in button
49              WebElement SignInButton = driver.findElement(By.id("signIn"));
50              SignInButton.click();
51              
52// close the web browser
53              driver.close();
54              System.out.println("Test script executed successfully.");
55              
56// terminate the program
57              System.exit(0);
58       }
59}
The above code is equivalent to the textual scenario presented earlier.

Code Walkthrough

Import Statements:
1import org.openqa.selenium.WebDriver;
2import org.openqa.selenium.firefox.FirefoxDriver;
3import org.openqa.selenium.WebElement;
4import org.openqa.selenium.By;
Prior to the actual scripting, we need to import the above packages:
import org.openqa.selenium.WebDriver – References the WebDriver interface which is required to instantiate a new web browser.
import org.openqa.selenium.firefox.FirefoxDriver – References the FirefoxDriver class that is required instantiate a Firefox specific driver on the browser instance instantiated using WebDriver interface.
import org.openqa.selenium.WebElement – References to the WebElement class which is required to instantiate a new web element.
import org.openqa.selenium.By – References to the By class on which a locator type is called.
As and when our project would grow, it is evident and logical that we might have to introduce several other packages for more complex and distinct functionalities like excel manipulations, database connectivity, logging, assertions etc.
Object Instantiation
WebDriver driver = new FirefoxDriver();
We create a reference variable for WebDriver interface and instantiate it using FirefoxDriver class. A default Firefox profile will be launched which means that no extensions and plugins would be loaded with the Firefox instance and that it runs in the safe mode.
Launching the Web browser
driver.get(appUrl);
get() method is called on the WebDriver instance to launch a fresh web browser instance. The string character sequence passed as a parameter into the get() method redirects the launched web browser instance to the application URL.
Maximize Browser Window
driver.manage().window().maximize();
The maximize() method is used to maximize the browser window soon after it is re-directed to the application URL.
Fetch the page Title
driver.getTitle();
The getTitle() method is used to fetch the title of the current web page. Thus, the fetched title can be loaded to a string variable.
Comparison between Expected and Actual Values:
1if (expectedTitle.equals(actualTitle))
2              {
3                     System.out.println("Verification Successful - The correct title is displayed on the web page.");
4              }
5              else
6              {
7                     System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
8              }
The above code uses the conditional statement java constructs to compare the actual value and the expected value. Based on the result obtained, the print statement would be executed.
WebElement Instantiation
WebElement username = driver.findElement(By.id(“Email”));
In the above statement, we instantiate the WebElement reference with the help of “driver.findElement(By.id(“Email”))”. Thus, username can be used to reference the Email textbox on the user interface every time we want to perform some action on it.
Clear Command
username.clear();
The clear() method/command is used to clear the value present in the textbox if any. It also clears the default placeholder value.
------------
sendKeys Command
username.sendKeys(“TestSelenium “);
The sendKeys() method/command is used to enter/type the specified value (within the parentheses ) in the textbox. Notice that thesendKeys() method is called on the WebElement object which was instantiated with the help of element property corresponding to the UI element.
The above block of code enters the string “TestSelenium” inside the Email textbox on the Gmail application.
sendKeys is one of the most popularly used commands across the WebDriver scripts.
Click Command
SignInButton.click();
Like sendKeys(), click() is another excessively used command to interact with the web elements. Click() command/method is used to click on the web element present on the web page.
The above block of code clicks on the “Sign in” button present on the Gmail application.
Notes:
  • Unlike sendKeys() method, click() methods can never be parameterized.
  • At times, clicking on a web element may load a new page altogether. Thus to sustain such cases, click() method is coded in a way to wait until the page is loaded.
Close the Web Browser
driver.close();
The close() is used to close the current browser window.
Terminate the Java Program
System.exit(0);
The Exit() method terminates the Java program forcefully. Thus, remember to close all the browser instances prior terminating the Java Program.

Test Execution

The test script or simply the java program can be executed in the following ways:
#1. Under the Eclipse’s menu bar, there is an icon to execute the test script. Refer the following figure.
WebDriver tutorial 1
Make a note that only the class which is selected would be executed.
#2. Right click anywhere inside the class within the editor, select “Run As” option and click on the “Java Application”.
#3. Another shortcut to execute the test script is – Press ctrl + F11.
At the end of the execution cycle, the print statement “Test script executed successfully.” can be found in the console.

Locating Web Elements

Web elements in WebDriver can be located and inspected in the same way as we did in the previous tutorials of Selenium IDE. Selenium IDE and Firebug can be used to inspect the web element on the GUI. It is highly suggested to use Selenium IDE to find the web elements. Once the web element is successfully found, copy and paste the target value within the WebDriver code. The types of locators and the locating strategies are pretty much the same except for the syntax and their application.
In WebDriver, web elements are located with the help of the dynamic finders (findElement(By.locatorType(“locator value”))).
Sample Code:
driver.findElement(By.id(“Email”));
WebDriver tutorial 2

Locator Types and their Syntax

Locator TypeSyntaxDescription
iddriver.findElement
(By.id(“ID_of_Element”))
Locate by value of 
the “id” attribute
classNamedriver.findElement
(By.className
(“Class_of_Element”))
Locate by value of 
the “class” attribute
linkTextdriver.findElement
(By.linkText(“Text”))
Locate by value of the
text of the hyperlink
partialLinkTextdriver.findElement
(By.partialLinkText
(“PartialText”))
Locate by value of the
sub-text of the hyperlink
namedriver.findElement
(By.name
(“Name_of_Element”))
Locate by value of the
“name” attribute
xpathdriver.findElement
(By.xpath(“Xpath”))
Locate by value 
of the xpath
cssSelectordriver.findElement
(By.cssSelector
(“CSS Selector”))
Locate by value of
the CSS selector
tagNamedriver.findElement
(By.tagName(“input”))
Locate by value of
its tag name

Handling Dynamic Elements in Selenium WebDriver

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