info inside
info inside

Reputation: 15

How to get the anchor tag value and href value inside a header tag using selenium

My html page code consists alot of anchor tags, but i need to get all the href value inside the anchor tag and anchor tag value which are present inside a header tag of a div element, i'm using selenium in java to get the page source of the html.

The part of html code of my the webpage look like this :-

<a href="www.qq.com">qq</a>
<a href="www.ww.com">ww</a>
<a href="www.ee.com">ee</a>
<div class="hello">
<h2>
<a href="www.aa.com">aa</a>
<a href="www.ss.com">aa</a>
</h2>
<div>

The java code i'm using to retrieve the anchor tag values look like this :-

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

The output of the above code is look like this:-

a=www.qq.com
a=www.ww.com
a=www.ee.com
a=www.aa.com
a=www.ss.com

But the output i need is like this:-

a=www.aa.com , aa
a=www.ss.com , ss

I need to get the all the anchortag values and href values inside the hello class

Upvotes: 0

Views: 2030

Answers (1)

Grasshopper
Grasshopper

Reputation: 9058

Try this -- Use getText() and modified xpath to include hrefs inside the div with class hello. Assuming the particular div is the unique one with the class name.

List<WebElement> list = driver.findElements(By.xpath("//div[@class='hello']//a[@href]"));
            for (WebElement e : list) {
                String link = e.getAttribute("href");
                System.out.println(e.getTagName() + "=" + link + " , " + e.getText());
            }

Upvotes: 1

Related Questions