Skip Huffman
Skip Huffman

Reputation: 5459

CSS Selectors, Choose by CHILD values

Let say I have an html structure like this:

<html><head></head>
    <body>
            <table>
                    <tr>
                            <td>
                                    <table>
                                            <tr>
                                                    <td>Left</td>
                                            </tr>
                                    </table>
                            </td>
                            <td>
                                    <table>
                                            <tr>
                                                    <td>Center</td>
                                            </tr>
                                    </table>
                            </td>
                            <td>
                                    <table>
                                            <tr>
                                                    <td>Right</td>
                                            </tr>
                                    </table>
                            </td>
                    </tr>
            </table>
    </body>
</html>

I would like to construct CSS selectors to access the three sub tables, which are only distinguished by the contents of a table data item in their first row.

How can I do this?

Upvotes: 0

Views: 245

Answers (2)

kreativitea
kreativitea

Reputation: 1791

the .text method on an element returns the text of an element.

tables = page.find_elements_by_xpath('.//table')
contents = "Left Center Right".split()
results = []
for table in tables: 
    if table.find_element_by_xpath('.//td').text in contents: # returns only the first element
         results.append(table)

You can narrow the search field by setting 'page' to the first 'table' element, and then running your search over that. There are all kinds of ways to improve performance like this. Note, this method will be fairly slow if there are a lot of extraneous tables present. Each webpage will have it's quirks on how it chooses to represent information, make sure you work around those to gain efficiency.

You can also use list comprehension to return your results.

results = [t for t in tables if t.find_element_by_xpath('.//td').text in contents]

Upvotes: 1

Santoshsarma
Santoshsarma

Reputation: 5667

I think there no such method available in css selector to verify the inner text.

You can achieve that by using xpath or jQuery path.

xpath :

   "//td[contains(text(),'Left')]"

               or

     "//td[text()='Right']"

jQuery path

    jQuery("td:contains('Centre')")

Using below logic you can execute jQuery paths in WebDriver automation.

JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element=(WebElement)js.executeScript(locator);

Upvotes: 1

Related Questions