How to find elements by CSS selector in Selenium

CSS selectors are one of the most popular ways to parse HTML pages when web scraping. Using Selenium, to find elements by CSS selectors we can use driver.find_element() and driver.find_elements() methods:
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://httpbin.dev/html")

element = driver.find_element(By.CSS_SELECTOR, 'p')
# then we can get the element text
print(element.text)
"Availing himself of the mild, summer-cool weather that now reigned in these latitudes..."
# we can also get tag name and attributes:
print(element.tag_name)
print(element.get_attribute("class"))

# for multiple elements we need to iterate
for element in driver.find_elements(By.CSS_SELECTOR, 'p'):
    print(element.text)

driver.close()

Also see: How to find elements by XPath in Selenium

Related Articles

How to Parse XML

In this article, we'll explain about XML parsing. We'll start by defining XML files, their format and how to navigate them for data extraction.

PYTHON
CSS-SELECTORS
XPATH
DATA-PARSING
How to Parse XML

Ultimate CSS Selector Cheatsheet for HTML Parsing

Ultimate companion for HTML parsing using CSS selectors. This cheatsheet contains all syntax explanations with interactive examples.

CSS-SELECTORS
DATA-PARSING
Ultimate CSS Selector Cheatsheet for HTML Parsing

Web Scraping With Ruby

Introduction to web scraping with Ruby. How to handle http connections, parse html files for data, best practices, tips and an example project.

RUBY
HTTP
DATA-PARSING
CSS-SELECTORS
XPATH
INTRO
Web Scraping With Ruby

Web Scraping With NodeJS and Javascript

In this article we'll take a look at scraping using Javascript through NodeJS. We'll cover common web scraping libraries, frequently encountered challenges and wrap everything up by scraping etsy.com

NODEJS
HTTP
DATA-PARSING
CSS-SELECTORS
INTRO
Web Scraping With NodeJS and Javascript

Parsing HTML with CSS Selectors

Introduction to using CSS selectors to parse web-scraped content. Best practices, available tools and common challenges by interactive examples.

DATA-PARSING
CSS-SELECTORS
Parsing HTML with CSS Selectors

Bypass Proxy Detection with Browser Fingerprint Impersonation

Stop proxy blocks with browser fingerprint impersonation using this guide for Playwright, Selenium, curl-impersonate & Scrapfly

PROXIES
SELENIUM
PLAYWRIGHT
PUPPETEER
BLOCKING
Bypass Proxy Detection with Browser Fingerprint Impersonation