Introduction
Finding elements by CSS selector helps you pick exactly the part of a webpage you want to work with, like clicking a button or reading text.
element = driver.find_element(By.CSS_SELECTOR, "css_selector_here")element = driver.find_element(By.CSS_SELECTOR, "#submit-button")element = driver.find_element(By.CSS_SELECTOR, ".menu-item.active")element = driver.find_element(By.CSS_SELECTOR, "div.content > p:first-child")from selenium import webdriver from selenium.webdriver.common.by import By # Start the browser (make sure you have the driver installed) driver = webdriver.Chrome() # Open a simple webpage html = ''' <html lang="en"> <head><title>Test Page</title></head> <body> <button id="submit-button">Submit</button> <div class="menu-item active">Menu 1</div> <div class="menu-item">Menu 2</div> <div class="content"> <p>First paragraph</p> <p>Second paragraph</p> </div> </body> </html> ''' # Load the HTML content using data URL import base64 encoded_html = base64.b64encode(html.encode('utf-8')).decode('utf-8') url = f"data:text/html;base64,{encoded_html}" driver.get(url) # Find the submit button by CSS selector submit_button = driver.find_element(By.CSS_SELECTOR, "#submit-button") print(submit_button.text) # Should print 'Submit' # Find the active menu item active_menu = driver.find_element(By.CSS_SELECTOR, ".menu-item.active") print(active_menu.text) # Should print 'Menu 1' # Find the first paragraph inside content div first_para = driver.find_element(By.CSS_SELECTOR, "div.content > p:first-child") print(first_para.text) # Should print 'First paragraph' # Close the browser driver.quit()
driver.find_element(By.CSS_SELECTOR, "selector").element = driver.find_element(By.CSS_SELECTOR, "div#main > ul.items > li.active")
element = driver.find_element(By.CSS_SELECTOR, "#content .item[active]")
<input> elements inside a form with id "loginForm" that have both classes "input-field" and "required". Which CSS selector should you use with Selenium Python's find_elements method?.input-field.required.form#loginForm to select the form by id, then space to select descendants, then input.input-field.required for inputs with both classes.Pass the test and this pattern moves unknown