user3062055
user3062055

Reputation: 309

get href value (WebDriver)

How do I get a value from href?

like this eg:

<div id="cont"><div class="bclass1" id="idOne">Test</div>

    <div id="testId"><a href="**NEED THIS VALUE AS STRING**">
    <img src="img1.png" class="clasOne" />
    </a>

</div>
</div>
</div>

I need that value as string.

I've tried with this:

String e = driverCE.findElement(By.xpath("//div[@id='testId']")).getAttribute("href");
            JOptionPane.showMessageDialog(null, e);

But just returns NULL value...

Upvotes: 19

Views: 98745

Answers (2)

Nishant
Nishant

Reputation: 1142

If you got more than one anchor tag, the following code snippet will help to find all the links pointed by href

//find all anchor tags in the page
List<WebElement> refList = driver.findElements(By.tagName("a"));

   //iterate over web elements and use the getAttribute method to 
   //find the hypertext reference's value.

    for(WebElement we : refList) {
        System.out.println(we.getAttribute("href"));
    }

Upvotes: 2

pavanraju
pavanraju

Reputation: 673

You have pointed your element to 'div' instead of 'a'

Try the below code

driverCE.findElement(By.xpath("//div[@id='testId']/a")).getAttribute("href");

Upvotes: 51

Related Questions