0
0
Selenium Javatesting~5 mins

CSS selector syntax in Selenium Java

Choose your learning style9 modes available
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.
You want to click a button on a webpage during automated testing.
You need to check if a specific text appears inside a certain section.
You want to fill a form field by locating it precisely.
You want to verify the presence of an image or link on a page.
You want to select elements by their class, id, or attribute for testing.
Syntax
Selenium Java
tagname
.classname
#id
[attribute='value']
tagname.classname
parent > child
ancestor descendant
:first-child
:last-child
Use # for id, . for class, and square brackets for attributes.
Combine selectors to be more specific, like div.content or input[type='text'].
Examples
Selects an input element with the id 'username'.
Selenium Java
input#username
Selects all elements with the class 'btn-primary'.
Selenium Java
.btn-primary
Selects all p elements that are direct children of a div.
Selenium Java
div > p
Selects all a (link) elements with href exactly 'https://example.com'.
Selenium Java
a[href='https://example.com']
Sample Program
This page uses CSS selectors to style elements by id and class. The heading uses an id selector, paragraphs use class selectors. You will see different styles applied based on these selectors.
Selenium Java
<!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>
OutputSuccess
Important Notes
In Selenium, you can use CSS selectors to find elements quickly and precisely.
Remember that id selectors (#id) are unique and faster, so prefer them when possible.
Classes (.) can be shared by many elements, so combine them with tags for accuracy.
Summary
CSS selectors help find and style webpage elements easily.
Use # for id, . for class, and [] for attributes in selectors.
Combine selectors to be more specific and accurate.