Getting CSS properties of an element with Python & Selenium

Learn how to target an element and get its CSS properties.

# Import the modules we need

from selenium import webdriver
from selenium.webdriver.common.by import By

# Specify the target URL and driver

url = 'https://www.google.com'
DRIVER_BIN = "Webdrivers\msedgedriver.exe"
driver = webdriver.Edge(executable_path=DRIVER_BIN)

# Open a browser and visit the URL

driver.get(url)

# Specify the target element selector

element_selector = 'img.lnXdpd'

# Get the element

element = driver.find_element(By.CSS_SELECTOR, element_selector)

# Print the CSS width attribute

print(
    element.value_of_css_property('width')
)

# Close the browser session

driver.close()

The output from the above will be the property for the CSS width attribute for the Google logo:

272px

Posted

in

,

by

Tags: