Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 862
williamtroup Avatar asked Aug 21 '12 14:08

williamtroup


3 Answers

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.

like image 58
williamtroup Avatar answered Sep 28 '22 11:09

williamtroup


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.

like image 37
chucksmash Avatar answered Sep 28 '22 10:09

chucksmash


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]')
like image 43
ecoe Avatar answered Sep 28 '22 10:09

ecoe