Marco
Marco

Reputation: 76

WebDriver - Python - How many elements in a table

I grab text from some elements on a table (TableExemple) with Selenium :

 element1 = driver.find_element_by_xpath("//table[@id='TableExemple']/tbody/tr[2]/td").text
 element2 = driver.find_element_by_xpath("//table[@id='TableExemple']/tbody/tr[3]/td").text
 element3 = driver.find_element_by_xpath("//table[@id='TableExemple']/tbody/tr[4]/td").text
 element4 = driver.find_element_by_xpath("////table[@id='TableExemple']/tbody/tr[5]/td").text

In some cases, only element1 is present on the table.

How to check if others elements exist, to avoid error?

It´s possible to count how many elements have the table ( like .options attribute for a drop-down menu : WebDriver - Python - How many elements in a drop-down menu)?

Thanks

Upvotes: 1

Views: 3391

Answers (2)

robert arles
robert arles

Reputation: 183

I've found it best to first do something like:

table_el = driver.find_elements_by_css('#TableExample')

I like css, second only to ID's. This use of find_elements doesn't throw an exception when it finds nothing (note the plural 'elements') Then with that returned list, possibly empty, go through the 'tr' elements:

if len(table_el.find_elements_by_css('tr')) < 1:
    return False  # or something more useful
trlist = list()
for tr in table_el.find_elements_by_css('tr'):
    trlist.append(tr)

Upvotes: 1

alecxe
alecxe

Reputation: 473863

You can use find_elements_by_xpath() to find multiple elements and call len() on the result:

cells = driver.find_elements_by_xpath("//table[@id='TableExemple']/tbody/tr[position() > 1]/td")
print(len(cells))

How to check if others elements exist, to avoid error?

You can catch NoSuchElementException being raised by find_element_by_xpath():

from selenium.common.exceptions import NoSuchElementException

try:
    element1 = driver.find_element_by_xpath("//table[@id='TableExemple']/tbody/tr[2]/td").text
    element2 = driver.find_element_by_xpath("//table[@id='TableExemple']/tbody/tr[3]/td").text
    element3 = driver.find_element_by_xpath("//table[@id='TableExemple']/tbody/tr[4]/td").text
    element4 = driver.find_element_by_xpath("//table[@id='TableExemple']/tbody/tr[5]/td").text
except NoSuchElementException as e:
    print "Element Not Found", e

Upvotes: 1

Related Questions