【问题标题】:How to get attribute of element from Selenium?如何从 Selenium 获取元素的属性?
【发布时间】:2015-07-31 05:31:24
【问题描述】:

我正在使用 Python 中的 Selenium。我想获取 <select> 元素的 .val() 并检查它是否符合我的预期。

这是我的代码:

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 文档似乎有很多关于选择元素的内容,但没有关于属性的内容。

【问题讨论】:

  • selenium-python-docs, 7.11 get_attribute(name) 可能会完成这项工作,尽管我认为我实际上并没有使用过它。试一试!

标签: python selenium selenium-webdriver webdriver getattribute


【解决方案1】:

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

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

    红宝石

    element.attribute("attribute name")
    

    C#

    element.GetAttribute("attribute name");
    

    【讨论】:

      【解决方案3】:

      由于最近开发的Web 应用程序 正在使用JavaScriptjQueryAngularJSReactJS 等,因此有可能通过 检索元素的属性Selenium 您必须先诱导 WebDriverWaitWebDriver 实例与滞后的 Web 客户端Web 浏览器 同步,然后再尝试检索任何属性。

      一些例子:

      • 蟒蛇:
        • 要从 visible 元素(例如 <h1> 标记)中检索任何属性,您需要将 expected_conditions 用作 @987654327 @如下:

          attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
          
        • 要从 interactive 元素(例如 <input> 标记)中检索任何属性,您需要将 expected_conditions 用作 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 Attribute Reference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-26
        相关资源
        最近更新 更多