CSS Selectors in Selenium Webdriver

HOME

(By.cssSelector("input#email"))
(By.cssSelector("#email"))
  • HTML tag – HTML tag of the element being accessed
  • # – The hash sign is use to symbolize ID attribute. It is mandatory to use hash sign if ID attribute is use to create CSS Selector.
  • Value of ID attribute – It is the value of an ID attribute that access. A hash sign always precedes the value of ID.

If two or more web elements have the same HTML tag and attribute value, the first element marked in the page source will identify.

2) Located by Class

Syntax

(By.cssSelector("input.inputtext"))
  • HTML tag = HTML tag of the element being accessed
  • . = the dot sign should always be present when using CSS with class
  • class = class of the element being accessed

3) Located by Attribute

(By.cssSelector("input[type='email']"))
  • HTML tag = HTML tag of the element being accessed
  • [ and ] = square brackets within which a specific attribute and its corresponding value will be placed
  • attribute = attribute to be used, preferable unique to the element
  • value = corresponding value of the chosen attribute.

4) Located by  ID/Class and attribute

(By.cssSelector("input.inputtext[name='email']")
  • HTML tag = HTML tag of the element being accessed
  • . = the dot sign should always be present when using a CSS with class
  • class = class of the element being accessed
  • [ and ] = square brackets within which a specific attribute and its corresponding value will be placed
  • attribute = attribute to be used, preferable unique to the element
  • value = corresponding value of the chosen attribute.

5) Located by Sub String Matches

CSS in Selenium has an interesting feature of allowing partial string matches using ^$, and *.

a) Starts with (^): To select the element, we would use ^ which means ‘starts with’.

(By.cssSelector("input[name^='em']"))
  • ^– Symbolic notation to match a string using prefix.

Prefix – It is the string based on which match operation is performed. The likely string is expected to start with the specified string

b) Ends with ($): To select the element, we would use $ which means ‘ends with’.

Syntax

(By.cssSelector("input[name$='il']"))
  • $ – Symbolic notation to match a string using suffix.
  • The suffix – It is the string based on which match operation is perform. The likely string is expect to ends with the specified string.

c) Contains (*): To select the element, we would use * which means ‘sub-string’.

Syntax

(By.cssSelector("input[name*='rst']"))
 
(By.cssSelector("input:contains('rst')")

– This is used to match the sub-string

6) Locating child element

Here, id =”content” is the parent locator. It will go to first div as child or sub child, then again div as child or sub child, and third div as child or sub child. Then it will go to div class _4bl7 _m-_ which further go to div class _ihd _3ma mbs _6n _6s _6v.

Syntax

(By.cssSelector("#content>div>div>div>div._4bl7._m-_>div._ihd._3ma.mbs._6n._6s._6v"))

Locating nth Child:

To locate the element with text ‘Female’, we use nth type css.

Syntax

(By.cssSelector("#u_0_13 > span:nth-child(1) > label"))

To select the last child element, i.e. ‘Male’, we can use.

Syntax

(By.cssSelector("#u_0_13 > span:last-child> label"))

Now, let’s write a small program to show the use of CSS Selectors. This program is it we have done for XPath , the only difference is the use of CSS Selectors to identify the web elements.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.time.Duration;

public class Selenium_Demo {

    protected static WebDriver driver;

    public static void main(String[] args) {

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        driver = new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        driver.get("https://opensource-demo.orangehrmlive.com/");
        driver.manage().window().maximize();

        //CSS Selectors for TextBox
        driver.findElement(By.cssSelector("input.oxd-input[name='username'")).sendKeys("Admin");

        driver.findElement(By.cssSelector("input.oxd-input[name='password'")).sendKeys("admin123");

        driver.findElement(By.cssSelector("button[type='submit'")).click();
        
        driver.close();
    }
}

Locators in Selenium – Locate by ID, ClassName, Name, TagName, LinkText, PartialLinkText

HOME

In this tutorial, we will use http://www.facebook.com for showing the use of different locators

How to find web elements?

1)  Locating by ID

Find the input element with ID.

Syntax

driver.findElement(By.id(“email”))

 

2)  Locating by ClassName

 Find the input element with name of class

Syntax 

driver.findElement(By.ClassName("inputtext"))

3)  Locating by TagName

Find the input element with TagName

Syntax 

driver.findElement(By.tagName("select"))

4)  Locating by Name

Find the input element with matching name attribute.

Syntax 

driver.findElement(By.name("email"))

5)  Locating by Linktext

Find the link element with matching visible text

Syntax

driver.findElement(By.linkText("Forgot account?"))

Find the link element with partial matching visible text

Syntax

driver.findElement(By.partialLinkText("Forgot "))

7)  XPath

Full form of XPath is XML Path. It is used to locate a web element on a web page using HTML DOM structure 

Syntax

By.xpath("//tagname[@Attribute = ‘value’]")

//: select the current node.
tagname: name of the tag of a particular node.
@: to select attribute.
Attribute: name of the attribute of the node.
Value: value of the attribute

There are 2 types of Xpath:-

1) Absolute Path
2) Relative Path

Absolute Path – It is the direct way to find any element. But as name suggest, it needs to be absolute. Any change made in the path will fail the xpath, result tool will not be able to locate the we element on the page.

Syntax

driver.findElement(By.xpath("//*[@id='yDmH0d']/div/div/div[2]/div[2]/div/div/div/div/div/div/ form/content/section/div/content/div/div/div/div/div/input"))

Relative Path –Relative XPath begins from the current location and is prefixed with a “//”. It starts from the middle of the DOM structure. To know more about XPath, click here

Syntax

By.xpath("//input[@name='identifier']")

8)  CSS Selectors 

CSS Selectors are string patterns used to identify an element based on a combination of HTML tag, id, class, and attributes. Locating by CSS Selector is more complicated than the previous methods, but it is the most common locating strategy of advanced Selenium users because it can access even those elements that have no ID or name. To know more about CSS, click here

Below is an example that shows how to use different locators. In this example, we have used Id, name, className, tagName, partialLinkText and LinkText locators.

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.time.Duration;
import java.util.List;

public class Automation_Practice_Form {

    protected static WebDriver driver;
    public static void main(String[] args) {

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        driver = new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        driver.get("https://opensource-demo.orangehrmlive.com/");
        driver.manage().window().maximize();

        // Locate link by partialLinkText
        String PartialLinkText_Text = driver.findElement(By.partialLinkText("Orange")).getText();
        System.out.println("Text of PartialLinkText Locator is ->" + PartialLinkText_Text);

        // Locate FirstName by name
        driver.findElement(By.name("username")).sendKeys("Admin");

        // Locate LastName by id
        driver.findElement(By.name("password")).sendKeys("admin123");

        // Locate options of DropDown by tagName
        List<WebElement> linkName = driver.findElements(By.tagName("a"));
        System.out.println("List of Links:");
        for (WebElement link : linkName) {
            System.out.println(link.getText() + " - " +link.getAttribute("href"));
        }
        driver.close();
    }
}

How to Locate Elements in Chrome, Firefox and IE Browsers for creating Selenium Scripts

HOME

In my previous tutorials, we have discussed about various types of locators available in Selenium WebDriver, which are used to identify various web elements on a web page. Some of the locators widely used are Id, ClassName, Name, LinkText, PartialLinkText, XPath, CSS Selector and so on. In this blog, will study the mechanism to locate web elements on Google Chrome, Firefox and Internet Explorer.

Google Chrome

  1. First step is to launch the Chrome Browser with desired URL. Here, we have launched Chrome browser and accessed Facebook page. I want to find the locator of Email or Phone textbox, so I will click on that textbox, right click, and click on “Inspect”.

2. Take a note that “Element” tab highlighted in the screenshot. Thus, element tab is the one, which displays all the HTML properties belonging to the current web page. Navigate to the “Element” tab if it is not open by default on the launch.

3.  In the screenshot, we can see the HTML code of Email or Phone Textbox. Right click on this text and then again click on Copy where will see options like – Copy Selector, Copy XPath, Copy full XPath

Copy Selector will tell the CSS Selector path of the WebElement

#email

Copy XPath will tell the Xpath of the WebElement

//*[@id="email"]

Copy full XPath will tell the absolute path of the WebElement

/html/body/div[1]/div[2]/div/div/div/div/div[2]/form/table/tbody/tr[2]/td[1]/input

Firstly, we should instantiate a Chrome/Chromium session by doing the following:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
         
WebDriver driver = new ChromeDriver();

Set the path to the chromedriver

executableSystem.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Automation\\Drivers\\chromedriver_win32\\chromedriver.exe");

The chromedriver is implement as a WebDriver remote server that instructs the browser what to do by exposing Chrome’s internal automation proxy interface.

Firefox

1.   First step is to launch the Firefox Browser with desired URL, ie Facebook. I want to find the locator of Email or Phone textbox, so I will click on that textbox and right click and click on “Inspect Element (Q)”.

2.  Take a note that “Inspector” tab is highlight in the screenshot. Thus, element tab is the one, which displays all the HTML properties belonging to the current web page. Navigate to the “Inspector” tab if it is not open by default on the launch.  

3. In the screenshot, we can see the HTML code of Email or Phone Textbox. Right click on this text and then again click on Copy where will see options like – Copy CSS Selector, Copy XPath, Copy CSS Path

Copy CSS Path will tell the CSS path of the WebElement

html#facebook body.fbIndex.UIPage_LoggedOut._-kb._605a.b_c3pyn-ahh.gecko.win.x1.Locale_en_GB.cores-gte4._19_u.hasAXNavMenubar div#u_0_e._li div#pagelet_bluebar div#blueBarDOMInspector div._53jh div.loggedout_menubar_container div.clearfix.loggedout_menubar div.menu_login_container.rfloat._ohf form#login_form table tbody tr td input#email.inputtext.login_form_input_box

Copy Selector will tell the CSS Selector path of the WebElement

#email

Copy XPath will tell the Xpath of the WebElement

//*[@id="email"]
System.setProperty("webdriver.gecko.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\geckodriver-v0.26.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

Internet Explorer

      1.   First step is to launch the Firefox Browser with desired URL. Here, we have launched Firefox browser and accessed Facebook page. I want to find the locator of Email or Phone textbox, so I will click on that textbox, right click, and click on “Inspect Element”.

      2.   Take a note that “DOM Explorer” tab is highlight in the screenshot. Thus, element tab is the one, which displays all the HTML properties belonging to the current web page. Navigate to the “DOM Explorer” tab if it is not open by default on the launch.

System.setProperty("webdriver.ie.driver","C:\\Users\\SingVi04\\Desktop\\Automation\\Drivers\\IEDriverServer_x64_3.150.1\\IEDriverServer.exe"); 
WebDriver driver = new InternetExplorerDriver();