DEV Community

skptricks
skptricks

Posted on

CSS Selectors in Selenium WebDriver with Examples

Post Link : CSS Selectors in Selenium WebDriver with Examples

CSS Selector is the combination of an element selector and a selector value which identifies the web element within a web page. The composite of element selector and selector value is known as Selector Pattern. Selector Pattern is constructed using HTML tags, attributes and their values. The central theme behind the procedure to create CSS Selector and Xpath are very much similar underlying the only difference in their construction protocol.

In this post we are going to discuss how to use css selector in selenium WebDriver java. Most of the automation testers believe that using CSS selectors makes the execution of script faster compared to XPath locator. CSS Selector locator is always the best way to locate elements on the page. CSS is always same irrespective of browsers.

To learn more about CSS Sector, do visit the below page :
https://www.w3schools.com/cssref/css_selectors.asp

Some benefits of using CSS Selectors :
CSS Selector is faster (especially in IE).
CSS Selector more readable.
In terms of performance, CSS perform well as compared to XPATH.
NOTE : While selecting an element make sure that element should be unique, descriptive and unlikely to change.

Syntax for CSS Selector in selenium WebDriver :
driver.findElement(By.cssSelector("input[class='username']")).sendKeys("skptricks-3");
To identify the web element using css selector, we need to call cssSelector() method.

Check out below web page link, we are going to use this link for CSS Selector demonstration :
DEMO LINK :
https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html

Read more...

Top comments (0)