Python & Selenium - 如何在页面上找到所有元素 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20244691/
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
Python & Selenium - how do I find all element IDs on a page?
提问by jononomo
I know that I can use methods such as:
我知道我可以使用以下方法:
find_elements_by_tag_name()
find_elements_by_id()
find_elements_by_css_selector()
find_elements_by_xpath()
But what I would like to do is simply get a list of all the element IDs that exist in the page, perhaps along with the tag type they occur in.
但是我想要做的只是获取页面中存在的所有元素 ID 的列表,也许还有它们出现的标签类型。
How can I accomplish this?
我怎样才能做到这一点?
采纳答案by Arran
Not had to do this before, but thinking about it logically you could use XPath to do this (may be other ways, XPath is the first thing that appears into my head).
以前不必这样做,但从逻辑上考虑,您可以使用 XPath 来做到这一点(可能是其他方式,XPath 是我脑海中出现的第一件事)。
Use find_elements_by_xpathusing the XPath //*[@id](anyelement that has an ID of some sort).
使用find_elements_by_xpathXPath //*[@id](具有某种 ID 的任何元素)。
You could then iterate through the collection, and use the .tag_nameproperty of each element to find out what kindof element it is and the get_attribute("id")method/function to get that element's ID.
然后,您可以迭代通过收集,并使用.tag_name每个元素的属性,以找出什么样的元素是和get_attribute("id")方法/函数来获取该元素的ID。
Note: This is probably going to be quite slow. After all, you are asking for a lotof information.
注意:这可能会很慢。毕竟,您要求提供大量信息。
回答by russian_spy
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://google.com')
ids = driver.find_elements_by_xpath('//*[@id]')
for ii in ids:
#print ii.tag_name
print ii.get_attribute('id') # id name as string

