info inside info inside - 1 year ago 179
Java Question

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="">qq</a>
<a href="">ww</a>
<a href="">ee</a>
<div class="hello">
<a href="">aa</a>
<a href="">aa</a>

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

But the output i need is like this:- , aa , ss

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

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download