Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting anchor tag from html using Java

I have several anchor tags in a text,

Input: <a href="http://stackoverflow.com" >Take me to StackOverflow</a>

Output: http://stackoverflow.com

How can I find all those input strings and convert it to the output string in java, without using a 3rd party API ???

like image 493
Ebbu Abraham Avatar asked Jul 19 '26 09:07

Ebbu Abraham


1 Answers

There are classes in the core API that you can use to get all href attributes from anchor tags (if present!):

import java.io.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

public class HtmlParseDemo {
   public static void main(String [] args) throws Exception {

       String html =
           "<a href=\"http://stackoverflow.com\" >Take me to StackOverflow</a> " +
           "<!--                                                               " +
           "<a href=\"http://ignoreme.com\" >...</a>                           " +
           "-->                                                                " +
           "<a href=\"http://www.google.com\" >Take me to Google</a>           " +
           "<a>NOOOoooo!</a>                                                   ";

       Reader reader = new StringReader(html);
       HTMLEditorKit.Parser parser = new ParserDelegator();
       final List<String> links = new ArrayList<String>();

       parser.parse(reader, new HTMLEditorKit.ParserCallback(){
           public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
               if(t == HTML.Tag.A) {
                   Object link = a.getAttribute(HTML.Attribute.HREF);
                   if(link != null) {
                       links.add(String.valueOf(link));
                   }
               }
           }
       }, true);

       reader.close();
       System.out.println(links);
   }
}

which will print:

[http://stackoverflow.com, http://www.google.com]
like image 104
Bart Kiers Avatar answered Jul 21 '26 00:07

Bart Kiers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!