【问题标题】:Selenium webdriver: How do I find ALL of an element's attributes?Selenium webdriver:如何找到元素的所有属性?
【发布时间】:2015-02-03 02:32:56
【问题描述】:

在 Python Selenium 模块中,一旦我有一个 WebElement 对象,我就可以使用 get_attribute() 获取其任何属性的值:

foo = elem.get_attribute('href')

如果名为'href' 的属性不存在,则返回None

我的问题是,我怎样才能得到一个元素所有属性的列表?似乎没有get_attributes()get_attribute_names() 方法。

我正在为 Python 使用 Selenium 模块的 2.44.0 版本。

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    不可能使用 selenium webdriver API,但你可以execute a javascript code to get all attributes:

    driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)
    

    演示:

    >>> from selenium import webdriver
    >>> from pprint import pprint
    >>> driver = webdriver.Firefox()
    >>> driver.get('https://stackoverflow.com')
    >>> 
    >>> element = driver.find_element_by_xpath('//div[@class="network-items"]/a')
    >>> attrs = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)
    >>> pprint(attrs)
    {u'class': u'topbar-icon icon-site-switcher yes-hover js-site-switcher-button js-gps-track',
     u'data-gps-track': u'site_switcher.show',
     u'href': u'//stackexchange.com',
     u'title': u'A list of all 132 Stack Exchange sites'}
    

    为了完整起见,另一种解决方案是获取标签的 outerHTML 并使用 HTML 解析器解析属性。示例(使用BeautifulSoup):

    >>> from bs4 import BeautifulSoup
    >>> html = element.get_attribute('outerHTML')
    >>> attrs = BeautifulSoup(html, 'html.parser').a.attrs
    >>> pprint(attrs)
    {u'class': [u'topbar-icon',
                u'icon-site-switcher',
                u'yes-hover',
                u'js-site-switcher-button',
                u'js-gps-track'],
     u'data-gps-track': u'site_switcher.show',
     u'href': u'//stackexchange.com',
     u'title': u'A list of all 132 Stack Exchange sites'}
    

    【讨论】:

    • 知道为什么这没有包含在 W3C 规范中吗?忽略这一点似乎是短视的w3.org/TR/webdriver/#get-element-attribute
    • @raven 不确定,可能只是它没有被广泛使用。更常见的是,用户希望获得单个属性。不过,这是个好问题,谢谢。
    • 替代方案:lxml element.attrib 返回一个包含所有属性的漂亮可用字典。
    • 标签outerHTML 非常有用,可以传递给BeautifulSoup :)
    • 你能写出你想要的任何脚本吗?或者execute_script在某些方面受到限制?
    【解决方案2】:

    以下为我获取所有属性及其(有时转换为字符串)值的列表,至少使用 PhantomJS 或 Chrome 驱动程序:

    elem.get_property('attributes')[0]
    

    仅获取名称:

    x.get_property('attributes')[0].keys()
    

    【讨论】:

    • 发现不是数字0而是字符串:elem.get_property('attributes')['0']
    【解决方案3】:

    您可以使用 element.get_property() 方法找到。

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.get("https://www.ultimateqa.com/complicated-page/")
    
    logo = driver.find_element(By.XPATH, "//img[@id='logo']")
    attrs=[]
    for attr in logo.get_property('attributes'):
        attrs.append([attr['name'], attr['value']])
    print(attrs)
    

    输出:

    [['src', 'https://www.ultimateqa.com/wp-content/uploads/2019/01/horizontal_on_transparent_by_logaster-2.png'], ['alt', 'Ultimate QA'], ['id', 'logo'], ['data-height-percentage', '100'], ['data-actual-width', '912'], ['data-actual-height', '410']]
    

    【讨论】:

      【解决方案4】:

      这是我试图回答的问题。我只在google主页的搜索框上测试过。我利用@alecxe 上面关于'outerHTML' 的回答获得了html,我使用正则表达式([a-z]+-?[a-z]+_?)='?"? 来匹配属性名称。我认为只需要修改正则表达式以匹配越来越多的案例。但我们需要的基本名称是“等号后面的任何内容”。

      给定一个 webElement

      def get_web_element_attribute_names(web_element):
          """Get all attribute names of a web element"""
          # get element html
          html = web_element.get_attribute("outerHTML")
          # find all with regex
          pattern = """([a-z]+-?[a-z]+_?)='?"?"""
          return re.findall(pattern, html)
      

      在下面的代码上测试一下

      import re
      from selenium import webdriver
      
      driver = webdriver.Firefox()
      google = driver.get("http://www.google.com")
      
      driver.find_element_by_link_text("English").click()
      search_element = driver.find_element_by_name("q")
      get_web_element_attribute_names(search_element)
      

      输出:

      ['class', 'id', 'maxlength', 'name', 'autocomplete', 'title', 'value', 'aria-label', 'aria-haspopup', 'role', 'aria-autocomplete', 'style', 'dir', 'spellcheck', 'type']
      

      【讨论】:

        猜你喜欢
        • 2012-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        相关资源
        最近更新 更多