Introduction
CSS selectors help you find and style parts of a webpage easily. In Selenium, they help you find elements to test or interact with.
tagname .classname #id [attribute='value'] tagname.classname parent > child ancestor descendant :first-child :last-child
# for id, . for class, and square brackets for attributes.div.content or input[type='text'].input element with the id 'username'.input#username
.btn-primary
p elements that are direct children of a div.div > p
a (link) elements with href exactly 'https://example.com'.a[href='https://example.com']<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Selector Example</title> <style> .highlight { color: darkblue; font-weight: bold; } #main-title { font-size: 2rem; margin-bottom: 1rem; } p.note { font-style: italic; color: gray; } </style> </head> <body> <header> <h1 id="main-title">Welcome to CSS Selectors</h1> </header> <main> <section> <p class="note">This paragraph has a class 'note'.</p> <p class="highlight">This paragraph is highlighted using the 'highlight' class.</p> <p>This paragraph has no special class.</p> </section> </main> <footer> <p>Footer content here.</p> </footer> </body> </html>
submitBtn?# symbol is used to select elements by their id attribute.#submitBtn targets the element with id="submitBtn" exactly.active?. followed by the class name..active selects all elements with class="active".<input type="text" name="username" class="input-field" id="user" />
name?[attr='value'].input[name='username'] selects input elements with name="username" exactly.driver.findElement(By.cssSelector("div#main .content > p:first-child"));p element that is the first child inside an element with class content, which is inside a div with id main.#main, .content, child combinator >, and pseudo-class :first-child are valid CSS selectors supported by Selenium.button elements that have both the class btn and an attribute data-action equal to save. Which CSS selector is correct?button.btn[data-action='save'].Pass the test and this pattern moves unknown