How to find Elements by CSS Selector using Selenium?

Find Elements by CSS Selector

To find HTML Elements that match the given CSS Selector using Selenium in Python, call find_elements() method, pass By.CSS_SELECTOR as the first argument, and the CSS selector string (of the HTML Elements we need to find) as the second argument.

find_elements(By.CLASS_NAME, "css_selector_value")

find_elements() method returns all the HTML Elements, that match the given CSS selector, as a list.

If there is no elements by given CSS selector, find_elements() function returns an empty list.


Consider the below HTML document.


  <p>Paragraph 1</p>
  <div class="flat-button">Button 1</div>
  <div class="flat-button">Button 2</div>
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>

In the following program, we will find all the HTML elements whose tag name is div and class name is 'card' using CSS selector, and print those elements to the console.

Python Program (Selenium)

from import Service
from selenium import webdriver
from import By

service = Service(executable_path="/usr/local/bin/chromedriver")
#initialize web driver
with webdriver.Chrome(service=service) as driver:
    #navigate to the url
    #find elements by css selector
    elements = driver.find_elements(By.CSS_SELECTOR, 'div.card')
    for element in elements:


<div class="card">Card 1</div>
<div class="card">Card 2</div>


In this tutorial of Python Examples, we learned how to find all the HTML elements that match the given CSS selector, in webpage, using Selenium.