How to count the total number of frames in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

We can count the total number of frames in a page in Selenium with the help of find_elements method. While working on frames, we will always find the tagname in the html code and its value should be frame/iframe.

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

To retrieve all the elements with the tagname as frame or iframe 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 frames are 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.

Syntax

driver.find_elements_by_tag_name("frame")

Example

Code Implementation to count frames.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
#to get the list of frames present on the web page
l = driver.find_elements_by_tag_name('frame')
#print the count with the len method on console
print(len(l))
#to close the browser
driver.quit()
raja
Published on 29-Jul-2020 12:57:14
Advertisements