Java 按属性查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26304224/
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
Find element by attribute
提问by Kishore Banala
I am trying to find an element with Attribute. Well, I can find elements with Id, tagName, Xpath and all other predefined methods in Selenium. But, I am trying to write a method that specifically returns WebElement, given Attribute name and Value as input.
我正在尝试查找具有 Attribute 的元素。好吧,我可以在 Selenium 中找到带有 Id、tagName、Xpath 和所有其他预定义方法的元素。但是,我正在尝试编写一个专门返回 WebElement 的方法,将属性名称和值作为输入。
List<WebElement> elements = webDriver.findElements(By.tagName("Attribute Name"));
for(WebElement element : elements){
if(element.getText().equals("Value of Particular Attribute")){
return element;
}
else{
return null;
}
}
Assuming XPath is not an option, is there any other better ways to do this?
假设 XPath 不是一种选择,还有其他更好的方法来做到这一点吗?
采纳答案by ddavison
You can easily get this task accomplished with CSS.
您可以使用 CSS 轻松完成此任务。
The formula is:
公式为:
element[attribute='attribute-value']
So if you have,
所以如果你有,
<a href="mysite.com"></a>
You can find it using:
您可以使用以下方法找到它:
By.cssSelector("a[href='mysite.com']");
this works using any attribute possible.
这适用于任何可能的属性。
This page here gives good information on how to formulate effective css selectors, and matching their attributes: http://ddavison.io/css/2014/02/18/effective-css-selectors.html
此页面提供了有关如何制定有效的 css 选择器并匹配其属性的好信息:http: //ddavison.io/css/2014/02/18/effective-css-selectors.html
回答by Sizik
Use CSS selectors instead:
改用 CSS 选择器:
List<WebElement> elements = webDriver.findElements(By.cssSelector("*[attributeName='value']"));
Edit: CSS selectors instead of XPath
编辑:CSS 选择器而不是 XPath
回答by SiKing
I do not understand your requirement:
我不明白你的要求:
Assuming XPath is not an option ...
假设 XPath 不是一个选项......
If this was just an incorrectassumption on your part, then XPath is the perfectoption!
如果这只是您的错误假设,那么 XPath 是完美的选择!
webDriver.findElements(By.xpath("//element[@attribute='value']"))
Of course you need to replace element
, attribute
, and value
with your actual names. You can also find "any element" by using the wildcard:
当然,你需要更换element
,attribute
和value
与你的实际名称。您还可以使用通配符查找“任何元素”:
webDriver.findElements(By.xpath("//*[@attribute='value']"))
回答by Irshad
As per the documentation:
根据文档:
By.id
Locates elements by the ID attribute. This locator uses the CSS selector
*[id='$ID']
, notdocument.getElementById
. Where id is the ID to search
By.id
通过 ID 属性定位元素。此定位器使用 CSS 选择器
*[id='$ID']
,而不是document.getElementById
. 其中 id 是要搜索的 ID
so you can use the below code to search the DOM element with any given attribute as ID and value
因此您可以使用以下代码搜索具有任何给定属性作为 ID 和值的 DOM 元素
By.id("element[attribute='attribute-value']");