2012-04-24 3 views
6

में href लिंक और URL की सामग्री का पता लगाएं मैं इस लिंक पार्स करने के लिए करना चाहते हैं:जावा

<a href="http://www.google.fr">Link to google</a> 

आदेश दो परिणाम प्राप्त करने के:

Link = "http://www.google.fr" 
LinkName = "Link to google" 

मैं वास्तव में ऐसा करने के तरीके पता नहीं है , क्या इस समस्या को हल करने के लिए जावा में एक पुस्तकालय है?

अग्रिम धन्यवाद,

+1

http://stackoverflow.com/questions/2168610/which-html-parser-is-best और http://stackoverflow.com/questions/2129375/html-xml-parser-for-java – assylias

+0

आप एक्सएमएल पार्सर का उपयोग कर सकते हैं .. फिर उस 'ए' नोड को पार्स करें और मान पुनर्प्राप्त करें। –

+1

बहुत ही सरल HTML के लिए, आप केवल JVM –

उत्तर

1

यह करना होगा।

public class Parse 
{ 
    public static void main(String[] args) 
    { 
    String h = " <a href=\"http://www.google.fr\">Link to google</a>"; 
    int n = getIndexOf(h, '"', 0); 

    String[] a = h.substring(n).split(">"); 
    String url = a[0].replaceAll("\"", ""); 
    String value = a[1].replaceAll("</a", ""); 

    System.out.println(url + " - " + value); 
    } 

    public static int getIndexOf(String str, char c, int n) 
    { 
    int pos = str.indexOf(c, 0); 
    while (n-- > 0 && pos != -1) 
    { 
     pos = str.indexOf(c, pos + 1); 
    } 
    return pos; 
    } 
} 
+0

के साथ प्रदान किए गए डिफ़ॉल्ट HTMLParser का उपयोग कर सकते हैं यह खराब अभ्यास है। आपको चरित्र स्थिति के आधार पर बचना चाहिए। नूरलन के जवाब देखें। –

1

उपयोग jsoup पार्सर:

उदाहरण:

File input = new File("/tmp/input.html"); 
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/"); 

Element content = doc.getElementById("content"); 
Elements links = content.getElementsByTag("a"); 
for (Element link : links) { 
    String linkHref = link.attr("href"); 
    String linkText = link.text(); 
}