2

I want to get the numbers of rows of a table on a web page using selenium python. I tried the following way describe here: How to count no of rows in table from web application using selenium python webdriver

rows=len(driver.find_element_by_xpath("//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr"))

The result I get is the following:

rows=len(driver.find_element_by_xpath("//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr"))
TypeError: object of type 'FirefoxWebElement' has no len()

I don't understand what I misdo.

Thanks for your help

Guy
  • 46,488
  • 10
  • 44
  • 88
Laetis
  • 1,337
  • 3
  • 16
  • 28
  • 1
    For list use `find_elements_*` – Guy Feb 06 '20 at 08:47
  • "driver.find_elements_by_xpath": it's "elements" – Yun Feb 06 '20 at 08:47
  • indeed! that s a little s that change a lot! thanks! – Laetis Feb 06 '20 at 08:52
  • Does this answer your question? [How to count no of rows in table from web application using selenium python webdriver](https://stackoverflow.com/questions/14831041/how-to-count-no-of-rows-in-table-from-web-application-using-selenium-python-webd) – Sathish Feb 06 '20 at 14:59

2 Answers2

6

Method driver.find_element_by_xpath(...) returns you only the first child (row) of the table.

Change the line to driver.find_elements_by_xpath(...). It returns a list of elements. So the new code will be:

rows = driver.find_elements_by_xpath("//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr")
number_of_rows = len(rows)
0

find_element_by_xpath() would return a single element and as you were using FireFox, the first matching WebElement was returned which can be passed to len(). Hence you see the error:

TypeError: object of type 'FirefoxWebElement' has no len()

So instead of find_element_by_xpath() you need to to use find_elements_by_xpath() which would return a List.


Ideally, to extract the number of rows in js table using Selenium and Python you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following solutions:

  • Using XPATH:

    print(len(WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr")))))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352