Get the size of an element in Selenium


Selenium Python - Get size of element

In this tutorial, you will learn how to get the size of an element, using Selenium in Python.

To get the size of an element, i.e., height and width of the element, in Selenium Python, locate the required element, and read the size attribute of the element object. The size attribute returns the height and width as a dictionary.

element.size

The return value is

{'height': somevalue, 'width': somevalue}

Example

In this example, we shall consider loading the HTML file at path /tmp/selenium/index-13.html . The contents of this HTML file is given below.

<html>
 <body>
  <h2>Hello User!</h2>
  <div id="parent">
    <div id="child1">This is child 1.</div>
    <div id="child2">This is child 2.</div>
    <div id="child3">This is child 3.</div>
  </div>
 </body>
</html>

In the following program, we initialize a driver, load the specified URL, find the element with id="parent", and get its height and width using size property.

Python Program

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url
driver.get('/tmp/selenium/index-13.html')

# Find an element by its ID
element = driver.find_element(By.ID, 'parent')

# Get element size
size = element.size
print(size)

# Close the driver
driver.quit()

Output

Selenium Python - Get size of element

Summary

In this Python Selenium tutorial, we have given instructions on how to get the size of an element, with example programs.