Css locator in selenium

CSS Selector in Selenium: Locate Elements with Examples

This article will discuss and describe, with examples, how one can use CSS selectors in Selenium test scripts to identify web elements. It will also depict CSS selectors’ syntax in Selenium.

It is recommended to gain a deeper understanding of locators in Selenium before narrowing it down to CSS selectors in particular.

What is a CSS Selector?

The CSS Selector combines an element selector and a selector value that can identify particular elements on a web page. Like XPath in Selenium, CSS selectors can locate web elements without ID, class, or Name.

Types of CSS Selectors (with Examples)

There are five types of CSS Selectors in Selenium tests:

1. ID

In this example, the script will access the Email text box on the login form at Gmail.com.

The text box carries an ID attribute with the value “Email”. In this case, the ID attribute and its value are utilized to create a CSS selector that allows access to the text box.

How to create the Selenium CSS Selector for the web element

Locate the web element – Email textbox. The HTML tag here is “input” and the ID attribute’s value is “Email”. Combined, they refer to the Email textbox. This is the data required to create the CSS selector.

Читайте также:  Php zip extension windows

CSS selector in Selenium

Verify locator value

Type “css=input#Email”(locator value) in Selenium IDE. Click on the Find button. The Email text box is highlighted, verifying the locator value.

CSS selector in Selenium - Verify locator value

  • HTML tag: used to denote the web element to be accessed
  • #: used to symbolize the ID attribute. Note that the hash is mandatory in cases where ID attribute is used to create a CSS Selector.
  • Value of ID attribute: the value of the ID attribute being accessed. The hash always precedes this value.

When specifying CSS Selector in the target text box of Selenium IDE, ensure that it is preceded by “css=”.

Note: The first element marked in the page source will be identified if multiple web elements have the same HTML tag and attribute value.

2. Class

In this example, the script will access the “Stay signed in” checkbox that appears below the login form at Gmail.com.

The checkbox carries a Class attribute with the value “remember”. This Class attribute and value can be utilized to create a CSS selector that accesses the selected web element.

Here’s how to create a CSS Selector for the web element

Locate the web element – “Stay signed in” checkbox. The HTML tag, in this case, is “label” and the ID attribute’s value is “remember”. Combined, they refer to the “Stay signed in” checkbox.

Verify locator value

Type “css=label.remember”(locator value) in Selenium IDE. Click on the Find Button. The “Stay signed in” checkbox is highlighted, verifying the locator value.

CSS selector in Selenium - Verify locator value

  • . : The dot is used to symbolize the Class attribute. Note that the dot is mandatory in cases where a Class attribute is used to create a CSS Selector. A dot always precedes the value of the Class.

3. Attribute

In this example, the script will access the “Sign in” button located beneath the login form at Gmail.com.

The “Sign in” button carries a type attribute with the value “submit”. This attribute and its value can be utilized to create a CSS Selector that will access the preferred web element.

Here’s how to create a CSS Selector in Selenium for the Web Element

Locate the web element – “Sign in” button. The HTML tag, in this case, is “input”, the attribute is the type, and the attribute’s value is “submit”. Combined, they refer to the “Sign in” button.

Verify locator value

Type “css=input[type=’submit’]” (locator value) in Selenium IDE. Click on the Find Button. The “Sign in” button will be highlighted, verifying the locator value.

Attribute CSS selector in Selenium

  • Attribute: Used to create the CSS Selector. It can be a value, type, name, etc. It is best to select an attribute with a value that uniquely identifies the accessed web element.
  • Value of attribute: the value of the attribute that is being accessed.

4. Sub-string

In Selenium, CSS allows the matching of a partial string which offers a way to create CSS selectors utilizing sub-strings. This can be done in three ways.

Types of mechanisms used to match sub-strings

Match a prefix

This purpose is to correspond to the string by using a matching prefix.

  • ^ : the symbol used to match a string using a prefix
  • Prefix: the string based on which the match operation is performed.

If one intends to identify the “Password textbox”, the CSS Selector, in this case, would be:

Match a suffix

This purpose is to correspond to the string by using a matching suffix.

  • #: the symbol used to match a string using a suffix.
  • Suffix: the string based on which the match operation is performed.

Again, if one intends to identify the “Password textbox”, the CSS Selector, in this case, would be:

Match a substring

This purpose is to correspond to the string by using a matching substring.

  • *: the symbol to match a string using sub-string
  • Sub string: the string based on which the match operation is performed.

Again, if one intends to identify the “Password textbox”, the corresponding CSS Selector would be:

5. Inner text

Using inner text helps identify and create CSS Selectors in Selenium WebDriver by utilizing a string pattern that the HTML Tag manifests on the web page. This mechanism is used most frequently to locate web elements because of its simplified syntax.

In this example, focus on the “Forgot email?” hyperlink present beneath the login form at Gmail.com.

Login automation using Selenium Example

The anchor tag that represents this hyperlink has some text within it. This text can create a CSS Selector that locates the required web element.

  • : – the colon is used to symbolize the contains method
  • contains – the value of the Class attribute that is being accessed
    Update:The feature is deprecated and no longer supported by the W3C standard. CSS Selectors Level 3 standard is applicable across all major browsers.
  • text – the text displayed anywhere on the web page, irrespective of its location

It is helpful to find an element by CSS selectors, mainly because advanced developers and testers use it. By mastering it, one can use Selenium to its full potential, thus optimizing its abilities for automated Selenium testing.

Источник

Selenium CSS Selectors Examples

Last updated: 19 March 2020 Locating elements by CSS selectors is the preferred way as it is faster and more readable than XPath. This tutorial provides examples of how to locate web elements in Selenium using CSS selectors.

CSS Selectors by Attribute

WebElement firstName = driver.findElement(By.cssSelector("input[name='first_name']")); 

Id Attribute

driver.findElement(By.cssSelector("input#firstname")); //or driver.findElement(By.cssSelector("#firstname")); 

Class Attribute

driver.findElement(By.cssSelector("input.myForm")); //or driver.findElement(By.cssSelector(".myForm")); 

Note: Take extra care when using the . notation as there could be many web elements on the HTML source with the same class attribute.

Multiple Attributes

Sometimes there is a need to be more specific with the selection criteria in order to locate the correct element.

The value of the display could either be “none” or “block” depending on the ajax call. In this situation, we have to locate the element by both class and style. Example:

driver.findElement(By.cssSelector("div[class='ajax_enabled'] [style='display:block']")); 

Attribute NOT contain a specific value

In WebDriver, how do you find elements whose attribute contain values which you don’t want to select? This CSS selector example shows how NOT to select by specific attribute value Suppose you have many elements which share the same attribute and attribute value, but some of those elements have other variables appended to the value. e.g:

In the above snippet, we want to select an available day (i.e. the two last div elements) As can be seen, all four divs contain “calendar-day-“ but the first two also contain “unavailable” which we don’t want. The CSS selector for Not selecting the first two divs is

driver.findElement(By.cssSelector("div[class*=calendar-day-]:not([class*='unavailable'])"));" 

Locating Child Element

driver.findElement(By.cssSelector("div#logo img")); 

Multiple Child Elements

There are occasions when there are multiple child elements within the same parent element such as list elements

As can be seen, the individual list elements don’t have any id associated with them. To locate the element with text ‘Orange’, we have to use nth-of-type . Example:

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

Dynamically Generated Ids

We can use string matchers to locate elements with dynamically generated Ids. In this example, all the three div elements contain the word ‘random’.

Attribute Starts with

driver.findElement(By.cssSelector("div[id^='123']")); 

Attribute Ends with

driver.findElement(By.cssSelector("div[id$='456']")); 

Attribute Contains

driver.findElement(By.cssSelector("div[id*='_pattern_']")); 
driver.findElement(By.cssSelector("div:contains('_pattern_')")); 

Источник

CSS Selectors in Selenium Webdriver

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 like by Id , class , XPath , 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 .

CSS is preferred way of locating element as it is faster than Xpath.

1) Located by ID

(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

(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’.

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’.

  • $ – 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’.

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

* – This is used to match the sub-string

6) Locating child element

Here, 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.

(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.

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

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

(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 java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Selenium_Site < public static void main(String[] args) < System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.get("https://www.amazon.com//"); driver.manage().window().maximize(); //CSS for Search box by using ID driver.findElement(By.cssSelector("input#twotabsearchtextbox")).sendKeys("hard drive"); //CSS for search button by using class driver.findElement(By.cssSelector("input.nav-input")).click(); >>

Источник

Оцените статью