0
0
Selenium Pythontesting~5 mins

Getting element attributes in Selenium Python

Choose your learning style9 modes available
Introduction

We get element attributes to check or use details like id, class, or href from web page elements.

To verify if a button has the correct 'disabled' attribute before clicking.
To check the 'href' link of a navigation menu item.
To confirm the 'value' inside an input box before submitting a form.
To read the 'title' attribute that shows extra info on hover.
To ensure an image has the correct 'alt' text for accessibility.
Syntax
Selenium Python
element.get_attribute('attribute_name')
Replace 'attribute_name' with the exact name of the attribute you want to get.
If the attribute does not exist, it returns None.
Examples
Gets the 'disabled' attribute of a button with id 'submit'.
Selenium Python
button = driver.find_element(By.ID, 'submit')
disabled = button.get_attribute('disabled')
Gets the URL from the 'href' attribute of a link with class 'nav-link'.
Selenium Python
link = driver.find_element(By.CSS_SELECTOR, 'a.nav-link')
href = link.get_attribute('href')
Gets the current text inside an input box named 'username'.
Selenium Python
input_box = driver.find_element(By.NAME, 'username')
value = input_box.get_attribute('value')
Sample Program

This script opens a simple HTML page with a link, button, and input box. It gets and prints their attributes using get_attribute.

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

# Setup driver (make sure chromedriver is in PATH)

# Open a simple test page
html = '''
<html>
  <body>
    <a id="home-link" href="https://example.com/home" title="Home Page">Home</a>
    <button id="submit-btn" disabled>Submit</button>
    <input name="email" value="user@example.com" />
  </body>
</html>
'''

# Load the HTML content
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
driver.get('data:text/html;charset=utf-8,' + html)

# Get attributes
link = driver.find_element(By.ID, 'home-link')
href = link.get_attribute('href')
title = link.get_attribute('title')

button = driver.find_element(By.ID, 'submit-btn')
disabled = button.get_attribute('disabled')

input_box = driver.find_element(By.NAME, 'email')
value = input_box.get_attribute('value')

print(f"Link href: {href}")
print(f"Link title: {title}")
print(f"Button disabled attribute: {disabled}")
print(f"Input value: {value}")

driver.quit()
OutputSuccess
Important Notes

The 'disabled' attribute returns 'true' if present, otherwise None.

Always check if the attribute is None before using it to avoid errors.

Using headless mode runs the browser without opening a window, good for automated tests.

Summary

Use get_attribute to read any attribute from a web element.

It helps verify element properties during tests.

Remember to handle cases where the attribute might not exist.