0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

How to Get Attribute of Element in Selenium: Simple Guide

In Selenium, use the get_attribute() method on a web element to retrieve the value of a specific attribute. For example, element.get_attribute('href') returns the URL from a link element's href attribute.
๐Ÿ“

Syntax

The get_attribute() method is called on a web element object and takes the attribute name as a string argument. It returns the attribute's value as a string or None if the attribute does not exist.

  • element: The web element found by Selenium.
  • get_attribute('attribute_name'): Method to get the attribute value.
  • attribute_name: The name of the attribute you want to retrieve, e.g., 'href', 'class', 'id'.
python
value = element.get_attribute('attribute_name')
๐Ÿ’ป

Example

This example shows how to open a webpage, find a link element, and get its href attribute value using Selenium WebDriver in Python.

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

# Setup WebDriver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open example page
driver.get('https://example.com')

# Find the first link element
link = driver.find_element(By.TAG_NAME, 'a')

# Get the href attribute of the link
href_value = link.get_attribute('href')
print('Link href attribute:', href_value)

# Close the browser
driver.quit()
Output
Link href attribute: https://www.iana.org/domains/example
โš ๏ธ

Common Pitfalls

  • Trying to access an attribute that does not exist returns None, so always check for None before using the value.
  • Using element.attribute_name (dot notation) does NOT work to get attributes in Selenium; always use get_attribute().
  • Make sure the element is found before calling get_attribute() to avoid errors.
python
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

try:
    element = driver.find_element(By.ID, 'nonexistent')
    # Wrong: attribute access via dot notation (does not work)
    # value = element.href  # This will raise AttributeError

    # Right way:
    value = element.get_attribute('href')
except NoSuchElementException:
    print('Element not found')
Output
Element not found
๐Ÿ“Š

Quick Reference

Remember these tips when getting attributes in Selenium:

  • Use get_attribute('name') to get any attribute value.
  • Returns None if attribute is missing.
  • Works for standard and custom attributes.
  • Always ensure element is present before calling.
โœ…

Key Takeaways

Use element.get_attribute('attribute_name') to get an element's attribute value in Selenium.
If the attribute does not exist, get_attribute() returns None, so check before use.
Never use dot notation to access attributes; always use get_attribute().
Ensure the element is found before calling get_attribute() to avoid errors.
get_attribute() works for all attributes including standard and custom ones.