0

I am testing a webpage with Selenium IDE that contains a table. I would like to verify text in a table cell (row, column) via CSS selector. The HTML structure of the table is very simple. Here is a sample of the table where every row represents a different attribute of a person:

<html...>
  <head>
  </head>
  <body>
    <div class="pageBody">
      <table>
        <tbody>
          <tr>
            <td></td>
            <td>AGE</td>
            <td>49</td>
          </tr>
          <tr>
            <td></td>
            <td>WEIGHT</td>
            <td>165</td>
          </tr>
... and so on

In Selenium IDE, I am able to find "49" in the table row containing AGE using the following CSS selector:

(APPROACH 1) css=#pageBody table tbody tr:nth-child(1) td:nth-child(3)

However, if I am not certain every table will have the same number of rows (in the event of dynamically created tables based on data available for each person), I could change the pseudo selector from nth-child to contains:

(APPROACH 2) css=#pageBody table tbody tr:contains('AGE') td:nth-child(3)

The problem comes when I export these approaches as JUnit code. The following block of JUnit code works:

(using APPROACH 1)
WebDriver.findElement (By.cssSelector ("#pageBody table tbody tr:nth-child(1) td:nth-child(3)"))

where the following block of JUnit code fails:

(using APPROACH 2)
WebDriver.findElement (By.cssSelector ("#pageBody table tbody tr:contains('AGE') td:nth-child(3)"))

Does anyone know why the JUnit APPROACH 2 is failing to find the CSS selector where it is perfectly valid and works very well in Selenium IDE? Please ask questions for clarification. Thank you kindly for any light you can shed on this.

1 Answers1

1

As far as I know the selector :contains is not supported in CSS. To select elements based on textual content you should instead use XPath.

prestomanifesto
  • 12,528
  • 5
  • 34
  • 50
  • As mentioned above, the :contains works fine in Selenium IDE using CSS selectors to find page elements. Wouldn't this imply :contains is supported in CSS? – fuzzynavel Apr 09 '12 at 18:07
  • 2
    @fuzzynavel: No, `:contains()` was dropped from the CSS spec, whereas Selenium just happens to implement a previous revision of the spec that did describe `:contains()`. See [this answer](http://stackoverflow.com/a/4781167/106224). – BoltClock Apr 09 '12 at 18:20
  • So do you have any suggestions given the current specifications for CSS3 how one would reproduce the same functionality of contains() in order to verify text of '49' in a row with 'AGE' given the table structure above? Any hints on how the XPath for this would look? Thank you. – fuzzynavel Apr 10 '12 at 12:55
  • For XPath something like so: `//*[@id='pageBody']/table/tbody/tr[contains(., 'AGE')]/td[position()=3]` or a shorter version: `//tr[contains(., 'AGE')]/td[position()=3]` – prestomanifesto Apr 10 '12 at 15:16