Converting CSS to XPath
In web testing, effectively selecting elements within a webpage’s Document Object Model (DOM) is crucial. CheckView supports both CSS selectors and XPath expressions for this purpose. Understanding the differences and similarities between CSS and XPath can enhance your testing strategies. Below is a guide to converting common CSS selectors into their XPath equivalents.
1. Selecting Elements by Tag Name
| Description | CSS Selector | XPath Expression |
|---|
| Any element | * | //* |
| Any <span> element | span | //span |
| Any <section> element | section | //section |
2. Selecting Elements by Attribute
| Description | CSS Selector | XPath Expression |
|---|
| <input> with type equal to text | input[type=”text”] | //input[@type=”text”] |
| Elements with data-role starting with admin | [data-role^=”admin”] | //*[starts-with(@data-role, ‘admin’)] |
| Elements with data-id ending with 123 | [data-id$=”123″] | //*[substring(@data-id, string-length(@data-id) – string-length(‘123’) + 1) = ‘123’] |
| Elements with title containing tooltip | [title*=”tooltip”] | //*[contains(@title, ‘tooltip’)] |
3. Selecting Elements by ID
| Description | CSS Selector | XPath Expression |
|---|
| Element with ID header | #header | //*[@id=’header’] |
4. Selecting Elements by Class
| Description | CSS Selector | XPath Expression |
|---|
| Elements with class active | .active | //*[contains(concat(‘ ‘, normalize-space(@class), ‘ ‘), ‘ active ‘)] |
5. Selecting Elements by Text Content
| Description | CSS Selector | XPath Expression |
|---|
| <button> with exact text Submit | N/A | //button[text()=’Submit’] |
| <p> containing text Welcome | N/A | //p[contains(text(), ‘Welcome’)] |
6. Selecting Elements by Hierarchy
| Description | CSS Selector | XPath Expression |
|---|
| Direct child <li> of <ul> | ul > li | //ul/li |
| Descendant <a> within <nav> | nav a | //nav//a |
| Adjacent sibling <div> following a <header> | header + div | //header/following-sibling::div[1] |
Additional Tips
- CSS Pseudo-classes and Pseudo-elements: CSS selectors like ‘:nth-child()’ or ‘::after’ don’t have direct XPath equivalents. For instance, ‘div:nth-child(2)’ can be translated to ‘//div[position()=2]’ in XPath.
- Performance Considerations: CSS selectors are generally faster and more readable for simple selections. XPath offers more flexibility, especially for complex hierarchical selections or when selecting elements based on text content.
- Tooling: Utilize browser developer tools to test and refine your selectors. Most browsers allow you to test both CSS and XPath expressions directly in the console.
Selector strategy is one piece of building tests that survive site changes. See the rest of CheckView’s features.