J'ai me suis documenté et constaté qu'en fait, c'est la source DOM qu'il me faut.
J'ai donc trouvé sur le site ce programme, écrit par Ioan Calapodescu, qui pourrait résoudre mon problème:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class LiensXHTML{
public static List<Element> getLinks(String xhtmlUrl) throws Exception{
List<Element> liens = new ArrayList<Element>();
InputStream stream = null;
try{
DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
fabrique.setValidating(true);
DocumentBuilder constructeur = fabrique.newDocumentBuilder();
URL url = new URL(xhtmlUrl);
stream = url.openStream();
Document document = constructeur.parse(stream);
Element racine = document.getDocumentElement();
String tag = "a";
NodeList liste = racine.getElementsByTagName(tag);
for(int i=0; i<liste.getLength(); i++){
Element e = (Element)liste.item(i);
if(e.hasAttribute("href"))liens.add(e);
}
}catch(Exception e){
System.out.println(e.getLocalizedMessage());
throw e;
}finally{
try{stream.close();}catch(Exception e){}
return liens;
}
}
public static void main(String[] args){
try{
String url = "http://www.w3.org/";
List<Element> liens = getLinks(url);
for(Element lien : liens){
String href = lien.getAttribute("href");
String texte = lien.getTextContent();
texte = (texte!=null)?texte:href;
System.out.println("Lien "+texte+" pointe sur "+href);
}
}catch(Exception e){
e.printStackTrace();
}
}
} |
Mais il y a un couac car le programme donne ceci:
Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
J'ai cherché sur le net ce qu'il en est mais je n'ai rien trouvé de concluant.
Quelqu'un a-t-il une idée sur ce qui cloche ?
Merci.
Partager