get_attribute Method

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.

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 the href the attribute value of the located <a> (anchor) element.

Common Use Cases

  • href for link URLs
  • src for image URLs
  • class for CSS class names
  • id for unique identifiers
  • data-* attributes for custom data