How to get attribute of element from Selenium?

江枫思渺然 提交于 2019-11-26 01:08:45

问题


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 docs seem to have plenty about selecting elements but nothing about attributes.


回答1:


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")



回答2:


Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");



回答3:


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 form 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 form 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

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



来源:https://stackoverflow.com/questions/30324760/how-to-get-attribute-of-element-from-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!