Introduction
We get element attributes to check or use details like id, class, or href from web page elements.
We get element attributes to check or use details like id, class, or href from web page elements.
element.get_attribute('attribute_name')button = driver.find_element(By.ID, 'submit') disabled = button.get_attribute('disabled')
link = driver.find_element(By.CSS_SELECTOR, 'a.nav-link') href = link.get_attribute('href')
input_box = driver.find_element(By.NAME, 'username') value = input_box.get_attribute('value')
This script opens a simple HTML page with a link, button, and input box. It gets and prints their attributes using get_attribute.
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()
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.
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.
get_attribute('href') do when called on a web element?get_attribute is used to read the value of a specified attribute from a web element.element using Selenium in Python?get_attribute with an underscore, all lowercase.get_attribute('class'), which matches the correct syntax exactly.element = driver.find_element(By.ID, 'submit-btn')
value = element.get_attribute('type')
print(value)<button id='submit-btn' type='submit'>Send</button>, what will be printed?type='submit'.get_attribute('type') returns the string 'submit' as that is the attribute's value.element = driver.find_element(By.NAME, 'email')
email_value = element.get_attribute('value')
print(email_value)None even though the input field has a value. What is the most likely cause?<input type='checkbox' id='agree' checked>
Pass the test and this pattern moves unknown