9m. WebDriver – Locating elements: Part 3b (by cssSelector contd.)

Hi ninjas! This post is a continuation of our previous post, “9l. WebDriver – Locating elements: Part 3a (by cssSelector)”. Before going any further, please make sure you take a good look at it.

The last two ways of using cssSelector locators which are yet to be discussed are,

  1. Locating child elements
  2. Matching by sub-string

Without further ado, let’s get into action!

1. Locating child elements

It is also possible to locate child elements using cssSelectors.

Let us consider the HTML code,

Anchor tag is the child element of ‘div’. To access the child element,

Using Id:

driver.findElement(By.cssSelector("div#child a"));

# represents ‘id’ and the child element tag is written after a space.

Using class:

driver.findElement(By.cssSelector("div.bg_main a"));

. represents ‘class’

Example: Let us locate the first name text box on the Gmail account sign up page.

Right click on the ‘first name’ text box and select inspect element to get the corresponding HTML code which is as below,

<label id="recovery-email-label">
	<strong>Your current email address</strong>
	<input name="RecoveryEmailAddress" id="RecoveryEmailAddress" value="" 	
               spellcheck="false" type="text">
</label>

‘label’ tag’s child element can be accessed with its ‘input’ tag and ‘name’ attribute.

Code:

driver.findElement(By.cssSelector("label#recovery-email-label input[name='RecoveryEmailAddress']"));

In case a parent element has multiple child elements (e.g. dropdowns), and they don’t have an ‘id’ or ‘class’ or such attributes to identify, then “nth-of-type” is used to locate a specific child element.

Consider the HTML code,

<ul id="pets">
   <li>Cat</li>
   <li>Dog</li>
   <li>Birds</li>
</ul>

To identify the child element ‘Dog’,

Code:

driver.findElement(By.cssSelector("ul#pets li:nth-of-type(2)"));

Matching by sub-string

cssSelectors help us to locate elements with sub-strings as well.

Match a prefix (or) begins with

In order to match an element with a known prefix,

Syntax: driver.findElement(By.cssSelector(“tag_name[attribute^=’prefix_value_of_attribute’]”));

Explanation: Locates the element starting with the given prefix. It is represented by ‘^’ symbol.

Considering the below code,

<input value="" name="LastName" id="LastName" spellcheck="false" type="text">

We can see that the ‘input’ tag has an ‘id’ attribute as ‘LastName’. To locate this element, we can specify that find the ‘id’ attribute value that begins with ‘Last’.

Code:

driver.findElement(By.cssSelector("input[id^='Last']"));

Match a suffix (or) ends with

In order to match an element with a known suffix,

Syntax: driver.findElement(By.cssSelector(“tag_name[attribute$=’suffix_value_of_attribute’]”));

Explanation: Locates the element ending with the given suffix. It is represented by ‘$’ symbol.

Considering the below code,

<input name="PasswdAgain" id="PasswdAgain" type="password">

We can see that the ‘input’ tag has a ‘name’ attribute as ‘PasswdAgain’. To locate this element, we can specify that find the ‘name’ attribute value that ends with ‘Again’.

Code:

driver.findElement(By.cssSelector("input[name$='Again']"));

Match a sub-string

In order to match an element with a sub-string,

Syntax: driver.findElement(By.cssSelector(“tag_name[attribute*=’substring_of_attribute_value’]”));

Explanation: Locates the element containing the given sub-string. It is represented by ‘*’ symbol.

Considering the below code,

<input name="PasswdAgain" id="PasswdAgain" type="password">

We can see that the ‘input’ tag has a ‘name’ attribute as ‘PasswdAgain’. To locate this element, we can specify that find the ‘name’ attribute value that contains ‘wdAg’.

Code:

driver.findElement(By.cssSelector("input[name*='wdAg']"));

Overall picture

Let us see a test case implementing the different ways to use cssSelector locators covered as part of this and the previous post,

Scenario

  1. Open Firefox browser.
  2. Navigate to google account creation page
  3. Locate ‘First Name’ text box with HTML tag and name attribute
  4. Enter ‘testFirst’ as the first name
  5. Locate ‘Last Name’ text box with a value that begins with a sub-string
  6. Enter ‘testLast’ as last name
  7. Locate ‘Creat a password’ text box with HTML tag , type and name attributes
  8. Enter ‘Pass1234!’ as password
  9. Locate ‘Confirm your password’ text box with a value that contains a sub-string
  10. Enter ‘Pass1234!’ as confirmation password
  11. Locate ‘Mobile phone’ text box with HTML tag and class attribute
  12. Enter ‘9496543210’ as the phone number
  13. Locate ‘Current email address’ text box with child element method
  14. Enter ‘[email protected]
  15. Verify JUnit pane for success result and eclipse IDE console output screen

JUnit code for this scenario is,

package com.blog.junitTests;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ElementLocatorTest3 {
        //Declaring variables
        private WebDriver driver; 
        private String baseUrl;

        @Before
        public void setUp() throws Exception{
            // Selenium version 3 beta releases require system property set up
            System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
                    + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
            // Create a new instance for the class FirefoxDriver
            // that implements WebDriver interface
            driver = new FirefoxDriver();
            // Implicit wait for 5 seconds
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            // Assign the URL to be invoked to a String variable
            baseUrl = "https://accounts.google.com/SignUp";
        }
        
        @Test
        public void testPageTitle() throws Exception{
            // Open baseUrl in Firefox browser window
            driver.get(baseUrl);
            // Locate 'First Name' text box by cssSelector: tag and name attribute
            // assign it to a variable of type WebElement
            WebElement firstName = driver.findElement(By.cssSelector("input[name='FirstName']"));
            // Clear the default placeholder or any value present
            firstName.clear();
            // Enter/type the value to the text box
            firstName.sendKeys("testFirst");
            //Locate 'Last Name' text box by cssSelector: begins with sub-string
            WebElement lastName = driver.findElement(By.cssSelector("input[id^='Last']"));
            lastName.clear();
            lastName.sendKeys("testLast");
            //Locate password text box by cssSelector: tag and type, name attributes
            WebElement pwd = driver.findElement(By.cssSelector("input[type='Password'][name='Passwd']"));
            pwd.clear();
            pwd.sendKeys("Pass1234!");
            //Locate 'Confirm your password' text box by cssSelector: contains sub-string
            WebElement confirmPwd = driver.findElement(By.cssSelector("input[name*='wdAg']"));
            confirmPwd.clear();
            confirmPwd.sendKeys("Pass1234!");
            // Locate Mobile phone text box by cssSelector: tag and class
            WebElement mobileNum = driver.findElement(By.cssSelector("input.i18n_phone_number_input-inner_input")); 
            mobileNum.clear();
            mobileNum.sendKeys("9496543210");
            //Locate "current email address" text box by cssSelector: child element method
            WebElement recoveryEmail = driver.findElement(By.cssSelector("label#recovery-email-label input[name='RecoveryEmailAddress']"));
            recoveryEmail.clear();
            recoveryEmail.sendKeys("[email protected]");
        }
        
         @After
          public void tearDown() throws Exception{
            // Close the Firefox browser
            driver.close();
        }
}

Execution result

The comments are clearly provided for each line of code and hence are self-explanatory.

by cssSelector output

In JUnit pane, the green bar shows that the test case is executed successfully. Also, no errors are logged in the console window.

Below image shows the final output executed in Firefox browser.

Browser output

That’s all for today ninjas! See you again in another post.

Have a great day!

1 Comment 9m. WebDriver – Locating elements: Part 3b (by cssSelector contd.)

  1. Suvvi

    I really like the way concepts are explained! Amazing write-up!! Sample scenarios and code make it all the more easier to understand.

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

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