Get Table data using WebDriver and Python

Following code prints table data. This is just an idea how you can traverse thru table.
your xpath should be something like : "//form[2]/table/tbody"

and you can call this function like ...

self.getTable("//form[2]/table/tbody")

def getTableVersion1(self,locator):

### Locate you table using xpath
table = self._selobj.find_element_by_xpath(locator)

#### This is just to debug....
#### This will print Webelement details like -
print table

### print row content. Entire row in one go.
for tr in table.find_elements_by_tag_name('tr'):
print "Text in TR is " + tr.text

### print cell value
for td in table.find_elements_by_tag_name('td'):
print "Text in TD is " + td.text

Following function prints table cell values.

def getTableversion2(self,locator):

table = self._selobj.find_element_by_xpath(locator)
print "\nEntire Table :\n***\n" + table.text + "\n***"

for tr in table.find_elements_by_tag_name('tr'): ### All rows in the
print "\nTR is " + tr.text ### Prints entire row, header row also...

for td in tr.find_elements_by_tag_name('td'): ### Search for TD tag
print "TD value " + td.text ### Print cell value
else:
print "No TD. May be TH row OR Empty Row"

Output:

Entire Table :
***
Name Domain/IP/Extension Description Keywords Last Modified
afda a.com 10/28/2012 13:53
test t.com 10/30/2012 11:46
***

TR is Name Domain/IP/Extension Description Keywords Last Modified
No TD. May be TH row OR Empty Row

TR is afda a.com 10/28/2012 13:53
TD value afda
TD value a.com
TD value
TD value
TD value 10/28/2012 13:53
TD value
No TD. May be TH row OR Empty Row

TR is test t.com 10/30/2012 11:46
TD value test
TD value t.com
TD value
TD value
TD value 10/30/2012 11:46
TD value
No TD. May be TH row OR Empty Row

To Get the header or field name, you need to search for 'th' instead of 'tr'.
=============================================================================
### number of rows in the given table.
def getRowCount(self,locator):
table = self._selobj.find_element_by_xpath(locator)
return (len(table.find_elements_by_tag_name('tr')))

### number of columns in the given table. Hope your table has TH row in it.

def getColCount(self,locator):
table = self._selobj.find_element_by_xpath(locator)
tr = table.find_elements_by_tag_name('tr')
return (len(tr[0].find_elements_by_tag_name('th')))

Comments

Popular posts from this blog

Selenium: File download handling.

Major Differences between Python and Java

Cypress V/S Selenium