Obtendo os links de um documento html
Aprenda nesta dica como fazer para obter todos os links de um documento html.
Obtendo os links de um documento html
Aprenda nesta dica como fazer para obter todos os links de um documento html.
public static String[] getLinks(String uriStr) {
List result = new ArrayList();try {
URL url = new URI(uriStr).toURL();
URLConnection conn = url.openConnection();
Reader rd = new InputStreamReader(conn.getInputStream());
EditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
kit.read(rd, doc, 0);
// Encontra todos os elementos que tenham A do documento HTML
HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
while (it.isValid()) {
SimpleAttributeSet s = (SimpleAttributeSet)it.getAttributes();
String link = (String)s.getAttribute(HTML.Attribute.HREF);
if (link != null) {
// adiciona o link encontrado na lista de links
result.add(link);
}
it.next();
}
} catch (MalformedURLException e) {
} catch (URISyntaxException e) {
} catch (BadLocationException e) {
} catch (IOException e) {
}
// Retorna todos os links encontrados
return (String[])result.toArray(new String[result.size()]);
}
Artigos relacionados
-
Artigo
-
Artigo
-
Artigo
-
Artigo
-
Artigo