2012-04-24 12 views
6

voglio analizzare questo link:Trova contenuto di link href e l'URL in Java

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

Al fine di ottenere due risultati:

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

io davvero non so come fare , c'è una libreria in Java per risolvere questo problema?

Grazie in anticipo,

+1

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

+0

È possibile utilizzare il parser XML .. quindi analizzare quel nodo 'a' e recuperare i valori. –

+1

Per HTML molto semplice, si può semplicemente usare l'HTMLParser predefinito fornito con JVM –

risposta

1

Questo farà.

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

Questa è una pratica scorretta. Dovresti evitare di dipendere dal posizionamento dei personaggi. Vedi la risposta di Nurlan. –

1

Uso jsoup parser:

esempio:

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(); 
} 
Problemi correlati