How to count the total number of tables in a page in Selenium with python?

We can count the total number of tables in a page in Selenium with the help of find_elements method. While working on any tables, we will always find the tagname in the html code and its value should be table (<table>).

This characteristic is only applicable to tables on that particular page and to no other types of UI elements like edit box, radio buttons and so on.

To retrieve all the elements with the tagname as a table we will use find_elements_by_tag_name() method. This method returns a list of web elements with the type of tagname specified in the method argument. In case there are no matching elements, an empty list will be returned.

After the list of tables is fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure.

Finally this length is printed on the console.




Code Implementation for counting the number of tables.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
#get method to launch the URL
#to refresh the browser
#to get the list of tables present on the web page
t = driver.find_elements_by_tag_name('table')
#print the count with the len method on console
#to close the browser

Updated on: 29-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started