有没有办法在 Python Selenium 中通过属性查找元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28426645/
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
Is there a way to find an element by attributes in Python Selenium?
提问by armnotstrong
I got a html snippet like this:
我得到了一个这样的 html 片段:
<input type="text" node-type="searchInput" autocomplete="off" value="" class="W_input" name="14235541231062">
The only unique identity of this element in the html is the attribute node-type="searchInput"
,so I want to locate it by using some methodof Python selenium sort of like this:
这个元素在 html 中唯一唯一的标识是属性node-type="searchInput"
,所以我想通过使用Python selenium 的某种方法来定位它,就像这样:
search_elem = driver.find_element_by_xxx("node-type","searchInput") # maybe?
I have checked the selenium(python) document for locating elemsbut didn't get a clue of how to locate this elem by the node-type
attr. Is there a explicit way to locate this elem in python selenium?
我已经检查了 selenium(python)文档来定位 elems,但没有得到如何通过node-type
attr定位这个 elem 的线索。有没有明确的方法可以在 python selenium 中找到这个 elem?
采纳答案by alecxe
You can get it by xpathand check the node-type
attribute value:
可以通过xpath获取并查看node-type
属性值:
driver.find_element_by_xpath('//input[@node-type="searchInput"]')
回答by Yaakov Bressler
Here's a method you could use:
这是您可以使用的方法:
save_items = []
for item in driver.find_elements_by_tag_name("input"):
# Get class
item_class = item.get_attribute("class")
# Get name:
item_name = item.get_attribute("name")
# And so on...
# Check for a match
if item_class == "W_input" and item_name == "14235541231062":
# Do your operation (or add to a list)
save_items.append(item)