How to get an attribute of an element from Selenium

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.

266047 次浏览

You are probably looking for get_attribute(). An example is shown 给你 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")

巨蟒

element.get_attribute("attribute name")

爪哇咖啡

element.getAttribute("attribute name")

Ruby *

element.attribute("attribute name")

C #

element.GetAttribute("attribute name");

由于最近开发的 网上应用程式使用的是 JavaScriptJQueryAngularJSReactJS等等,因此有可能通过 检索一个元素的属性,在试图检索任何属性之前,你必须诱导 等等使 WebDriver实例与滞后的 网络客户端(即 网页浏览器)同步。

一些例子:

  • 巨蟒:
    • 要从 可见元素(例如 <h1>标签)检索任何属性,您需要使用 预期 _ 条件作为 visibility_of_element_located(locator),如下所示:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • 要从 互动元素(例如 <input>标记)检索任何属性,您需要使用 预期 _ 条件作为 Element _ to _ be _ clickable (locator),如下所示:

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

HTML 属性

Below is a list of some attributes often used in HTML

HTML Attributes

注意 : 每个 HTML 元素的所有属性的完整列表列于: < a href = “ https://www.w3school s.com/tag/ref _ Attributes.asp”rel = “ nofollow noReferrer”> HTML Attribute Reference