Selenium Webdriver:如何找到元素的所有属性? [英] Selenium webdriver: How do I find ALL of an element's attributes?

查看:524
本文介绍了Selenium Webdriver:如何找到元素的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the Python Selenium module, once I have a WebElement object I can get the value of any of its attributes with get_attribute():

foo = elem.get_attribute('href')

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

If the attribute named 'href' doesn't exist, None is returned.

我的问题是,如何获取元素具有的所有属性的列表?似乎没有get_attributes()get_attribute_names()方法.

My question is, how can I get a list of all of the attributes that an element has? There doesn't seem to be a get_attributes() or get_attribute_names() method.

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

I'm using version 2.44.0 of the Selenium module for Python.

推荐答案

使用硒Webdriver API不可能 ,但是您可以

It is not possible using a selenium webdriver API, but you can 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 ):


For completeness sake, an alternative solution would be to get the tag's outerHTML and parse the attributes using an HTML parser. Example (using 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'}

这篇关于Selenium Webdriver:如何找到元素的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆