Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

java - Find element by attribute

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can easily get this task accomplished with 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...