CSS selectors help you find parts of a webpage easily. They tell your code exactly which elements to look at.
0
0
CSS selector syntax in Selenium Python
Introduction
You want to click a button on a webpage automatically.
You need to check if a specific text is shown on a page.
You want to fill out a form by finding input boxes.
You want to test if a menu item appears after clicking.
You want to get a list of all images on a page.
Syntax
Selenium Python
tagname #id .classname parent > child [attribute='value']
Use tagname to select all elements of that type, like all div tags.
Use #id to select one unique element by its ID.
Examples
Selects all <div> elements on the page.
Selenium Python
div
Selects the element with the ID
submit-button.Selenium Python
#submit-buttonSelects all elements with the class
menu-item.Selenium Python
.menu-item
Selects all text input boxes that are direct children of a <form>.
Selenium Python
form > input[type='text']
Sample Program
This page has a heading with an ID, paragraphs with classes, and a button with an ID. You can use CSS selectors to find these elements easily.
Selenium Python
<!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: red; } </style> </head> <body> <h1 id="main-title">Welcome</h1> <p class="intro">This is a simple page.</p> <p class="intro highlight">This paragraph is highlighted.</p> <div> <button id="submit-button">Submit</button> </div> </body> </html>
OutputSuccess
Important Notes
IDs should be unique on a page, so #id selects one element.
Classes can be shared by many elements, so .classname can select many.
The > symbol means direct child, not any descendant.
Summary
CSS selectors help you pick elements on a webpage by tag, ID, class, or attribute.
Use simple selectors for easy targeting and combine them for precise selection.
They are very useful for automating tasks like clicking buttons or reading text.