When using Selenium for web automation testing, CSS Selectors are a highly effective method for locating elements on the page. Selecting elements based on attribute values is a common usage of CSS Selectors. Below are some basic steps and examples demonstrating how to use CSS Selectors to select elements based on attribute values.
Steps:
- Import the Selenium Library: First, ensure that Selenium is installed in your Python environment and that the appropriate WebDriver is imported.
- Launch the WebDriver: Initialize a browser instance, such as Chrome.
- Open the Web Page: Use the
getmethod to open the target web page. - Locate Elements Using CSS Selector: Use the
find_element_by_css_selectormethod to locate elements using CSS Selectors.
CSS Selector Basic Syntax:
tagname[attribute='value']: Selects elements with the specified attribute and value.tagname[attribute*='value']: Selects elements where the attribute value contains the specified text.tagname[attribute^='value']: Selects elements where the attribute value starts with the specified text.tagname[attribute$='value']: Selects elements where the attribute value ends with the specified text.
Examples:
Assume we have an HTML page containing the following tags:
html<input type="text" id="username" name="username" /> <button type="submit" class="btn" id="submit-button">Submit</button>
Example 1: Selecting Elements by ID
pythonfrom selenium import webdriver driver = webdriver.Chrome() driver.get('http://example.com') # Use CSS Selector to locate elements by ID username_input = driver.find_element_by_css_selector("input[id='username']")
Example 2: Selecting Elements by Class
pythonsubmit_button = driver.find_element_by_css_selector("button.btn")
Example 3: Selecting Elements by Attribute Value Starting with
python# Select buttons where the type attribute starts with 'sub' submit_buttons = driver.find_elements_by_css_selector("button[type^='sub']")
By understanding these basic concepts and examples, you can effectively use Selenium and CSS Selectors to select elements on the page based on attribute values. This helps you precisely locate and interact with elements during automation testing.