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(); >>
How to Use CSS Selector in Selenium WebDriver | 13 Examples
Selenium Webdriver is very powerful to automate web applications. We can identify web elements in Selenium Webdriver using various locators and CSS Selector is one of them.CSS Selector in Selenium acts as the best workaround to find an element when we don’t have an option to locate an element using Id or Name. Also, it is faster and simpler than XPath.To know more about XPath please refer exclusive article on Xpath XPath in Selenium WebDriver with Example .In the following examples, we will see how to use CSS Selectors in Selenium.
CSS Selectors by Attribute
Suppose we have an Html tag with the following attributes.
The syntax to locate elements by attribute are as follows
tagName[attributename=’attributeValue’]
Since name might not be a unique property on the web we can combine more than one attribute to find an element uniquely. For that, the syntax is as follows:
CSS Selector Tag and ID Attribute
In CSS, a hash (#) notation refers to the id attribute of an element.
Syntax 1:
Syntax 2:
CSS Selector Class Attribute
A dot (.) notation is used to refer to the class attribute of an element.
Handling Multiple Classes or Space Character in Class Name
Suppose we have an Html tag with the following attributes.
In the above HTML tag, three classes (abc, pqr, and xyz) are being used for the single text. box. You can not write a statement like By.cssSelector(“.abc pqr xyz”) to identify an element.If you write such code Selenium will throw NoSuchElementException error. Developers can use such class having multiple class names for different elements on the page. Out of all the class names, a few of the names might be unique. To handle such a scenario we have to join the classes using a dot(.) notation unless the required element is identified uniquely. The following are the possible ways to refer to the element.
Locate Elements with Sub-strings or Partial Match
Using CSS locators, we can also locate elements with some matching patterns or sub-strings. It becomes very helpful to identify elements with dynamically generated ids. This is achieved by using three special characters ^, $, and *.
‘^’ symbol, represents the starting text in a string.
‘$’ symbol represents the ending text in a string.
‘*’ symbol represents contains text in a string.
Let’s consider a web page has the following HTML Tags