Search code examples
htmlseleniumattributeshref

Using selenium to access attribute text


I'm really new to selenium and this is probably really simple, but what i'm trying to do is store the '2017 League Table Ranking: 25th" text inside this attribute to a string in java:

<a href="/league-tables/rankings">
 2017 League Table Ranking: 25th
</a>

public void findRanking() throws Exception {
  String ranking = driver.findElement(By.xpath("(//a[contains(@href, '/league-tables/rankings')])")).getAttribute(href) ;

}

This gives me the link to the href that the attribute is using, and is the closest i've got to getting an output kind of right. I've tried simply getting the text of the element above, using the .getText() method but that returns nothing, where am i going wrong?


Solution

  • Since we now have a link to the page, I was able to create a unique locator. The problem was that there was more than one element that matched the locator and the first match wasn't the one you wanted. Since we don't need XPath here, I switched to a CSS selector. CSS selectors have better browser support, are faster, and I think are easier to create. This should work now.

    public String findRanking() {
        return driver.findElement(By.cssSelector("p.league-table-latest-rank > a[href='/league-tables/rankings']")).getText();
    }
    

    Here are some references for CSS selectors. I would suggest that you spend some time learning them. They are extremely powerful and should be your goto locator after By.id().

    W3C CSS Selector Reference

    Sauce Labs CSS Selector Tips


    Original answer with XPath

    .getText() should work on that element. It looks like you have an extra set of () in your XPath. Also, you should be able to use equals instead of contains(). There may be other links that contain that partial href that may be causing issues. I would try the below. I added a return and changed the return type to String.

    public String findRanking() {
        return driver.findElement(By.xpath("//a[@href='/league-tables/rankings']")).getText();
    }
    

    You can test your XPath in Chrome. Open the page and try $x("//a[@href='/league-tables/rankings']").length in the dev console and make sure it returns 1. If it's 0 then something is wrong with the locator. If it's > 1 then you'll have to further narrow the focus of your locator. Find a unique parent that has an ID or something unique.