Python Selenium webdriver:如何找到元素的所有属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27307131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium webdriver: How do I find ALL of an element's attributes?
提问by Al Sweigart
In the Python Selenium module, once I have a WebElement
object I can get the value of any of its attributes with get_attribute()
:
在 Python Selenium 模块中,一旦我有了一个WebElement
对象,我就可以使用以下命令获取其任何属性的值get_attribute()
:
foo = elem.get_attribute('href')
If the attribute named 'href'
doesn't exist, None
is returned.
如果命名的属性'href'
不存在,None
则返回。
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.
我的问题是,如何获取元素具有的所有属性的列表?似乎没有get_attributes()
orget_attribute_names()
方法。
I'm using version 2.44.0 of the Selenium module for Python.
我正在为 Python 使用 Selenium 模块的 2.44.0 版。
采纳答案by alecxe
It is not possibleusing a selenium webdriver API, but you can execute a javascript codeto get all attributes:
使用 selenium webdriver API是不可能的,但您可以执行 javascript 代码来获取所有属性:
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)
Demo:
演示:
>>> 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'}
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
):
为了完整起见,另一种解决方案是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'}
回答by joeln
The following gets a list of all attributes and their (sometimes translated to strings) values for me, using the PhantomJS or Chrome driver at least:
以下为我获取所有属性及其(有时转换为字符串)值的列表,至少使用 PhantomJS 或 Chrome 驱动程序:
elem.get_property('attributes')[0]
To just get the names:
只需获取名称:
x.get_property('attributes')[0].keys()
回答by chidimo
Here is my attempt at an answer. I do only tested it on the search box of google's homepage. I made use of @alecxe's answer above about 'outerHTML' Having obtained the html, I used a regular expression ([a-z]+-?[a-z]+_?)='?"?
to match the attribute names. I think the regex would just have to be modified to match an increasing number of cases. But the essential name we need is "whatever is behind the equal sign."
这是我对答案的尝试。我只在谷歌主页的搜索框中测试过它。我利用了@alecxe 上面关于“outerHTML”的回答 获得了 html 后,我使用了一个正则表达式([a-z]+-?[a-z]+_?)='?"?
来匹配属性名称。我认为只需要修改正则表达式以匹配越来越多的案例。但是我们需要的基本名称是“等号后面的任何内容”。
Given a webElement
给定一个 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)
Test it on the below code
在下面的代码上测试
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)
output:
输出:
['class', 'id', 'maxlength', 'name', 'autocomplete', 'title', 'value', 'aria-label', 'aria-haspopup', 'role', 'aria-autocomplete', 'style', 'dir', 'spellcheck', 'type']
回答by Ararat Avagyan
You can find using element.get_property()method.
您可以使用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)
Output:
输出:
[['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']]