Uziii
Uziii

Reputation: 841

How to use the text between HTML tags to access an element - Selenium WebDriver

I have following HTML code.

<span class="ng-binding" ng-bind="::result.display">All Sector ETFs</span>

<span class="ng-binding" ng-bind="::result.display">China Macro Assets</span>

<span class="ng-binding" ng-bind="::result.display">Consumer Discretionary (XLY)</span>

<span class="ng-binding" ng-bind="::result.display">Consumer Staples (XLP)</span>

As it can be seen that tags are all the same for every line except the text between the tags. How can I access each of the above line separately based on the text between tags.

Upvotes: 2

Views: 2344

Answers (4)

Rajnish Kumar
Rajnish Kumar

Reputation: 2938

Hi please do it like below

Way One

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();

List<WebElement> mySpanTags = driver.findElements(By.xpath("ur xpath"));
System.out.println("Count the number of total tags : " + mySpanTags.size());
    // print the value of the tags one by one 
    // or do whatever you want to do with a specific tag

for(int i=0;i<mySpanTags.size();i++){
System.out.println("Value in the tag is : " + mySpanTags.get(i).getText());
// either perform next operation inside this for loop
if(mySpanTags.get(i).getText().equals("Consumer Staples (XLP)")){
    // perform your operation here 
    mySpanTags.get(i).click(); // clicks on the span tag
        }
    }

    // or perform next operations on span tag here outside the for loop
    // in this case use index for a specific tag (e.g below)
    mySpanTags.get(3).click(); // clicks on the 4 th span tag

}

Way Two

find the tag directly //span[text()='Consumer Staples (XLP)']

Upvotes: 1

Saurabh Gaur
Saurabh Gaur

Reputation: 23845

You can use following xPath to find desired element based on text

String text = 'Your text';
//text may be ==>All Sector ETFs, China Macro Assets, Consumer Discretionary (XLY), Consumer Staples (XLP)
String xPath = "//*[contains(text(),'"+text+"')]";

By this you can find each elements..

Hope it will help you..:)

Upvotes: 2

Nodonutsforyou
Nodonutsforyou

Reputation: 458

You can use x-path function text() for that. For example

//span[text()="All Sector ETFs"]

to find first span

Upvotes: 2

noor
noor

Reputation: 3004

use the below as xpath

//span[text()='All Sector ETFs']

Upvotes: 2

Related Questions