119

我正在使用 Python 中的 Selenium。我想得到.val()一个<select>元素并检查它是否是我所期望的。

这是我的代码:

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?

我怎样才能做到这一点?Selenium 文档似乎有很多关于选择元素的内容,但没有关于属性的内容。

4

3 回答 3

177

您可能正在寻找get_attribute(). 这里也显示了一个示例

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")
于 2015-05-19T12:16:31.443 回答
65

Python

element.get_attribute("attribute name")

爪哇

element.getAttribute("attribute name")

红宝石

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");
于 2017-08-24T14:02:44.763 回答
11

由于最近开发的Web 应用程序使用JavaScriptjQueryAngularJSReactJS等,因此有可能通过Selenium检索元素的属性,您必须诱导WebDriverWait将WebDriver实例与滞后的Web 客户端同步,即之前的Web 浏览器试图检索任何属性。

一些例子:

  • Python:
    • 要从可见元素(例如<h1>标签)中检索任何属性,您需要使用expected_conditions as visibility_of_element_located(locator),如下所示:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • 要从交互式元素(例如<input>标签)中检索任何属性,您需要使用expected_conditions as element_to_be_clickable(locator),如下所示:

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

HTML 属性

下面是 HTML 中常用的一些属性列表

HTML 属性

注意:每个 HTML 元素的所有属性的完整列表,请参见:HTML 属性参考

于 2018-12-13T09:50:04.273 回答