How to get an attribute of an element from Selenium
Asked Answered
B

3

134

I'm working with Selenium in Python. I would like to get the .val() of a <select> element and check that it is what I expect.

This is my code:

def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?

How can I do this? The Selenium documentation seem to have plenty about selecting elements but nothing about attributes.

Blaubok answered 19/5, 2015 at 11:47 Comment(1)
selenium-python-docs, 7.11 get_attribute(name) might do the job, although I don't think I've actually used it. Give it a shot!Underwood
P
202

You are probably looking for get_attribute(). An example is shown here as well

def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?
    val = org.get_attribute("attribute name")
Provision answered 19/5, 2015 at 12:16 Comment(0)
P
77

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");
Pfister answered 24/8, 2017 at 14:2 Comment(0)
I
11

As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.

Some examples:

  • Python:
    • To retrieve any attribute from a visible element (e.g. <h1> tag) you need to use the expected_conditions as visibility_of_element_located(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • To retrieve any attribute from an interactive element (e.g. <input> tag) you need to use the expected_conditions as element_to_be_clickable(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
      

HTML Attributes

Below is a list of some attributes often used in HTML

HTML Attributes

Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference

Isopleth answered 13/12, 2018 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.