If I have the following HTML:
<tbody id="items">
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
<tr><td>Item 4</td></tr>
<tr><td>Item 5</td></tr>
<tr><td>Item 6</td></tr>
</tbody>
How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?
We can count the total number of rows in a table in Selenium. The rows of a table are represented by <tr> tag in html code. To get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned.
In Selenium, CSS allows the matching of a partial string which, offers a way to create CSS selectors utilizing sub-strings. This can be done in three ways. The purpose of this is to correspond to the string by using a matching prefix. Prefix: the string on the basis of which the match operation is performed.
You can use “tag:nth-of-type(n)”. It will select the nth tag element of the list. Syntax: . tree-branch>ul>li:nth-of-type(3) (Selects 3rd li element.)
Css has better performance and speed than xpath. Xpath allows identification with the help of visible text appearing on screen with the help of text() function. Css does not have this feature. Customized css can be created directly with the help of attributes id and class.
You can use nth-child selector:
#items tr:nth-child(4) {color:#F00;}
Live example: https://jsfiddle.net/7ow15mv2/1/
But no idea if it works with Selenium.
But according to docs it should.
Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With