I: Simple
Direct child
A direct child in XPATH is defined by the use of a “/“, while on CSS, it’s defined using “>”Examples:
//div/a
css=div > a
Child or subchild
If an element could be inside another or one it’s childs, it’s defined in XPATH using “//” and in CSS just by a whitespace.Examples:
//div//a
css=div a
Id
An element’s id in XPATH is defined using:“[@id='example']”
and in CSS using: “#”
Examples:
//div[@id='example']//a
css=div#example a
Class
For class, things are pretty similar in XPATH:“[@class='example']”
while in CSS it’s just “.”Examples:
//div[@class='example']//a
css=div.example a
II: Advanced
Next sibling
This is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the next adjacent element on the page that’s inside the same parent. Let’s show an example using a form to select the field after username.</input> </input>
css=form input.username + input
Attribute values
If you don’t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good example would be choosing the ‘username’ element of the form without adding a class.</input> </input> </input> </input>
css=form input[name='username']
css=input[name='continue'][type='button']
Choosing a specific match
CSS selectors in Selenium allow us to navigate lists with more finess that the above methods. If we have a ul and we want to select its fourth li element without regard to any other elements, we should use nth-child or nth-of-type.<p>Heading</p>
- Cat
- Dog
- Car
- Goat
css=ul#recordlist li:nth-of-type(4)
css=ul#recordlist li:nth-child(4)
css=ul#recordlist *:nth-child(4)
Sub-string matches
CSS in Selenium has an interesting feature of allowing partial string matches using ^=, $=, or *=. I’ll define them, then show an example of each:^= Match a prefix
css=a[id^='id_prefix_']
$= Match a suffix
css=a[id$='_id_sufix']
*= Match a substring
css=a[id*='id_pattern']
Matching by inner text
And last, one of the more useful pseudo-classes, :contains() will match elements with the desired text block:css=a:contains('Log Out')
No comments :
Post a Comment