Selenium Webdriver:如何找到元素的所有属性? [英] Selenium webdriver: How do I find ALL of an element's attributes?
问题描述
在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.
推荐答案
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屋!