按属性查找元素

我试图找到一个属性的元素。 好吧,我可以在Selenium中找到带有Id,tagName,Xpath和所有其他预定义方法的元素。 但是,我正在尝试编写一个专门返回WebElement的方法,给定Attribute name和Value作为输入。

List elements = webDriver.findElements(By.tagName("Attribute Name")); for(WebElement element : elements){ if(element.getText().equals("Value of Particular Attribute")){ return element; } else{ return null; } } 

假设XPath不是一个选项,还有其他更好的方法吗?

您可以使用CSS轻松完成此任务。

公式是:

 element[attribute='attribute-value'] 

所以,如果你有,

  

您可以使用以下方式找到它

 By.cssSelector("a[href='https://stackoverflow.com/questions/26304224/find-element-by-attribute/mysite.com']"); 

这可以使用任何可能的属性。

此页面提供了有关如何制定有效的css选择器以及匹配其属性的详细信息: http : //ddavison.io/css/2014/02/18/effective-css-selectors.html

我不明白你的要求:

假设XPath不是一个选项……

如果您只是一个不正确的假设,那么XPath是完美的选择!

 webDriver.findElements(By.xpath("//element[@attribute='value']")) 

当然,您需要使用实际名称替换elementattributevalue 。 您还可以使用通配符找到“任何元素”:

 webDriver.findElements(By.xpath("//*[@attribute='value']")) 

改为使用CSS选择器:

 List elements = webDriver.findElements(By.cssSelector("*[attributeName='value']")); 

编辑:CSS选择器而不是XPath