William Troup
William Troup

Reputation: 13131

Iterate through table in Selenium 2 WebDriver (python)

I have the following table layout in HTML (which changes accordingly):

<table class="other-table-style">

    <tr> 
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
    </tr>
    <tr>
      <td align="center" width="30%">Joe</td>
      <td align="center" width="30%">Bloggs</td>
      <td align="center" width="40%">28</td>
    </tr>
    <tr>
      <td align="center" width="30%">John</td>
      <td align="center" width="30%">Doe</td>
      <td align="center" width="40%">30</td>
    </tr>

</table>

I want to be able to iterate through this using Selenium 2.0 WebDriver, but I have not been able to find any good examples.

Any help would be greatly appreciated.

Upvotes: 9

Views: 28077

Answers (3)

chucksmash
chucksmash

Reputation: 5997

It seems like the person who posted this related question had code that would get you on the right track:

for (WebElement trElement : tr_collection) {
    List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
    System.out.println("NUMBER OF COLUMNS = " + td_collection.size());
    col_num = 1;          

    if (!td_collection.isEmpty() && td_collection.size() != 1 ) {  
        for (WebElement tdElement : td_collection) {
            System.out.println("Node Name=== " + tdElement.getAttribute("class")); 
            System.out.println("Node Value=== " + tdElement.getText());
            col_num++;
        }
    }

    row_num++;
}

Edit: I changed their code somewhat... they were accumulating the class of each td and the text it contained in a hashmap and then once they had gone through the entire table, adding that into a master hashmap. Also this is the Java variant of Selenium so you would have to port it over. The guts of it remain the same though - perhaps someone with more Selenium experience could give more info... I prefer to live over in WATIRland myself.

Upvotes: 2

ecoe
ecoe

Reputation: 5312

Here is an excellent tutorial for parsing tables (and links) using selenium. Though it is written in Java, the translation into Python is quite trivial.

for instance, to read row 2 column 2 of a table with the Python version of Selenium (2.41):

from selenium import webdriver
driver = webdriver.Ie()

# assuming you're connected to your web page of interest, do:
x = driver.find_element_by_xpath('//table/tbody/tr[2]/td[2]')

Upvotes: 1

William Troup
William Troup

Reputation: 13131

Used:

from selenium.webdriver.common.by import By

trs = driver.find_elements(By.TAG_NAME, "tr") 

tds = trs[1].find_elements(By.TAG_NAME, "td")

This allows looping through each one to do as desired.

Upvotes: 17

Related Questions