Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS selectors to access specific table rows with selenium

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)?

like image 362
wierddemon Avatar asked Dec 20 '10 22:12

wierddemon


People also ask

How do I find table rows in Selenium?

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.

Can we use CSS selector in Selenium?

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.

How do you access the nth element using the CSS selector in Selenium?

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.)

Is it better to use CSS selector or XPath?

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.


1 Answers

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).

like image 167
Flack Avatar answered Sep 17 '22 14:09

Flack