In Selenium with Python, the get_attribute()
method is used to retrieve the value of a specific attribute from an HTML element. This can be particularly useful when you need to access values like href
for links, src
for images, class
, id
, or other attributes of HTML elements.
- Selenium Features
- Selenium Installation
- Selenium Locators
- XPath Fundamentals
- CSS Selectors Methods
- Different Browsers Execution
- find_element & find_elements
- Check Enabled Status
- Check Displayed Status
- Check Selected Status
- Selenium Waits
- Send_keys Method
- Click Method
- Get Text
- Get Attribute Value
- Get Current URL
- Forward, Back, Refresh
- Take Screenshot
- Handle Browser Tabs
- Handle iframe
- Mouse Hover
- Context-Click
- Drag & Drop
- Handle Alerts
- Handle Dropdown
- Execute Javascript
- Scroll To element
- Headless Mode Execution
- Chrome Options
- Keyboard Action
Basic Syntax
element = driver.find_element(By.XPATH, 'your_xpath_here')
attribute_value = element.get_attribute('attribute_name')
Example Usage
Here’s an example of how you might use get_attribute()
to get the URL from a link:
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize the WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(10)
# Open a webpage
driver.get('https://sqatools.in/')
# Find an element and get its attribute
element = driver.find_element(By.XPATH, "//a[text()='Python Tutorials']")
href_value = element.get_attribute('href')
print("The link URL is:", href_value)
# Close the WebDriver
driver.quit()
In this example:
driver.find_element(By.XPATH, '//a[text()='Python Tutorials']')
locates an element with the XPath specified.element.get_attribute('href')
retrieves thehref
the attribute value of the located<a>
(anchor) element.
Common Use Cases
href
for link URLssrc
for image URLsclass
for CSS class namesid
for unique identifiersdata-*
attributes for custom data