title: How to get anchor tag href and anchor tag text inside a div using Selenium in Java
body: <p>My HTML code consists of multiple <code>div</code>s. Inside each <code>div</code> is a list of anchor tags. I need to fetch the <code>href</code> values and text values of the anchor tags that are in the <code>sub-container</code> <code>div</code>. I'm using Selenium to get the HTML code of the webpage.</p>
  
  <p>HTML code:</p>
  
  <pre><code>&lt;body&gt;
      &lt;div id="main-container"&gt;
          &lt;a href="www.one.com"&gt;One&lt;/a&gt;
          &lt;a href="www.two.com"&gt;Two&lt;/a&gt;
          &lt;a href="www.three.com"&gt;Three&lt;/a&gt;
  
          &lt;div id="sub-container"&gt;
              &lt;a href="www.abc.com"&gt;Abc&lt;/a&gt;
              &lt;a href="www.xyz.com"&gt;Xyz&lt;/a&gt;
              &lt;a href="www.pqr.com"&gt;Pqr&lt;/a&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>Java code:</p>
  
  <pre><code>List&lt;WebElement&gt; list = driver.findElements(By.xpath("//*[@href]"));
  for (WebElement element : list) {
      String link = element.getAttribute("href");
      System.out.println(e.getTagName() + "=" + link);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>a=www.one.com
  a=www.two.com
  a=www.three.com
  a=www.abc.com
  a=www.xyz.com
  a=www.pqr.com
  </code></pre>
  
  <p>Output I need:</p>
  
  <pre><code>a=www.abc.com , Abc
  a=www.xyz.com , Xyz
  a=www.pqr.com , Pqr
  </code></pre>