Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get href value (WebDriver)

Tags:

java

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...

like image 277
user3062055 Avatar asked Dec 14 '13 02:12

user3062055


2 Answers

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

Try the below code

driverCE.findElement(By.xpath("//div[@id='testId']/a")).getAttribute("href");
like image 50
pavanraju Avatar answered Oct 19 '22 23:10

pavanraju


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"));
    }
like image 36
Nishant Avatar answered Oct 20 '22 00:10

Nishant