2012-04-24 16 views
6

Quiero analizar este enlace:Encontrará los contenidos del enlace href y el URL en Java

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

Con el fin de obtener dos resultados:

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

Realmente no sé cómo hacer esto , ¿hay una biblioteca en Java para resolver este problema?

Gracias de antemano,

+1

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

+0

Puede usar el analizador XML ... luego analizar ese 'a' nodo y recuperar valores. –

+1

Para HTML muy simple, puede usar HTMLParser predeterminado provisto con JVM –

Respuesta

1

Esto va a hacer.

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

Esta es una mala práctica. Debes evitar depender del posicionamiento del personaje. Ver la respuesta de Nurlan. –

1

Uso jsoup analizador:

ejemplo:

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(); 
} 
Cuestiones relacionadas