How to get anchor tag href and anchor tag text inside a div using Selenium in Java

Karthik picture Karthik · Nov 16, 2016 · Viewed 8.6k times · Source

My HTML code consists of multiple divs. Inside each div is a list of anchor tags. I need to fetch the href values and text values of the anchor tags that are in the sub-container div. I'm using Selenium to get the HTML code of the webpage.

HTML code:

<body>
    <div id="main-container">
        <a href="www.one.com">One</a>
        <a href="www.two.com">Two</a>
        <a href="www.three.com">Three</a>

        <div id="sub-container">
            <a href="www.abc.com">Abc</a>
            <a href="www.xyz.com">Xyz</a>
            <a href="www.pqr.com">Pqr</a>
        </div>
    </div>
</body>

Java code:

List<WebElement> list = driver.findElements(By.xpath("//*[@href]"));
for (WebElement element : list) {
    String link = element.getAttribute("href");
    System.out.println(e.getTagName() + "=" + link);
}

Output:

a=www.one.com
a=www.two.com
a=www.three.com
a=www.abc.com
a=www.xyz.com
a=www.pqr.com

Output I need:

a=www.abc.com , Abc
a=www.xyz.com , Xyz
a=www.pqr.com , Pqr

Answer

Girish Bellamkonda picture Girish Bellamkonda · Nov 16, 2016

Try this,

List<WebElement> list = driver.findElements(By.xpath("//div[@id='sub-container']/*[@href]"));
        for (WebElement element : list) {
            String link = element.getAttribute("href");
            System.out.println(element.getTagName() + "=" + link +", "+ element.getText());
        }