按属性查找元素 [英] Find element by attribute

查看:113
本文介绍了按属性查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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;
    }
}

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

Assuming XPath is not an option, is there any other better ways to do this?

推荐答案

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

You can easily get this task accomplished with CSS.

公式为:

element[attribute='attribute-value']

所以,如果你有,

<a href="mysite.com"></a>

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

You can find it using:

By.cssSelector("a[href='mysite.com']");

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

this works using any attribute possible.

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

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

这篇关于按属性查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆