有没有办法在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:16:12  来源:igfitidea点击:

Is there a way to find an element by attributes in Python Selenium?

pythonselenium

提问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-typeattr. Is there a explicit way to locate this elem in python selenium?

我已经检查了 selenium(python)文档来定位 elems,但没有得到如何通过node-typeattr定位这个 elem 的线索。有没有明确的方法可以在 python selenium 中找到这个 elem?

采纳答案by alecxe

You can get it by xpathand check the node-typeattribute 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)