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.

Example

Consider the HTML document at the URL https://pythonexamples.org/tmp/selenium/index-58.html, with the following HTML content.

HTML Webpage

<html>
 <body>
  <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>
 </body>
</html>
Copy

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 selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-58.html')

# Find elements by CSS Selector
my_elements = driver.find_elements(By.CSS_SELECTOR, 'div.card')
for element in my_elements:
    print(element.get_attribute("outerHTML"))

# Close the driver
driver.quit()

Output

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

Summary

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

Related Tutorials

Quiz on Selenium

Q1. What is the method used to find web elements in Selenium Python?

Not answered

Q2. Which of the following is not a method to wait for a web element to load in Selenium Python?

Not answered

Q3. What is the method used to navigate back to the previous page in Selenium Python?

Not answered

Q4. What is the method used to switch to a different frame in Selenium Python?

Not answered

Q5. What is the method used to clear the text from an input field in Selenium Python?

Not answered
Code copied to clipboard successfully 👍