To get the `href` attribute value from an HTML element using Python and Selenium, you can use the `get_attribute` method of a WebElement object. Here’s an example of how to do it:

from selenium import webdriver

# Initialize the WebDriver (assuming you're using Chrome)
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get("https://www.example.com")

# Find the element whose href attribute you want to retrieve (e.g., a link)
element = driver.find_element_by_css_selector("a")  # You can use other locators too

# Get the href attribute value
href_value = element.get_attribute("href")

# Print or use the href value as needed
print("Href value:", href_value)

# Close the browser
driver.quit()

In this example:

  1. We import the necessary Selenium modules and initialize a WebDriver (assuming you’re using Chrome).
  2. We navigate to a webpage (replace “https://www.example.com” with the URL you’re interested in).
  3. We locate the HTML element whose `href` attribute you want to retrieve using a CSS selector. You can use other locators like `find_element_by_id`, `find_element_by_xpath`, etc., depending on your specific use case.
  4. We use the `get_attribute(“href”)` method on the WebElement (`element`) to retrieve the `href` attribute value.
  5. Finally, we print or use the `href_value` variable as needed.

Make sure to replace the CSS selector or locator in the `find_element_by_css_selector` method with the appropriate selector for the element you want to target on the webpage.

Support On Demand!

QA Automation