How to count the number of columns in a table in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

We can count the number of columns in a table in Selenium. The headers of a table are represented by <th> tag in html and always in the first row of the table. The rows are identified with <tr> tag in html. The total count of the number of column headers is mostly equal to the total number of columns. A <th> tag’s parent is always a <tr> tag.

The logic is to get all the headers. We shall use the locator xpath and then use find_elements_by_xpath method. The list of headers will be returned. Next we need to compute the size of the list with the help of len method.



The html code snippet of a table column count is as described below −


Code Implementation for getting total column count.

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
#get method to launch the URL
#to refresh the browser
# identifying the header from row1 having <th> tag
cols = driver.find_elements_by_xpath("//table/tbody/tr[1]/th")
# len method is used to get the size of that list
#to close the browser
Published on 29-Jul-2020 13:52:19