Extraction d'une page web XHTML
Bonjour,
Pour récupérer les liens d'une page web, j'utilise l'application suivante (java)
Code:
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 52 53 54 55 56 57 58 59 60 61
| import java.io.*;
import java.net.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class LinksRetrieve
{
// This method takes a URI which can be either a filename (e.g. file://c:/dir/file.html)
// or a URL (e.g. http://host.com/page.html) and returns all HREF links in the document.
public static void main(String args[])
{
String uriStr = "http://www.paris-turf.com/pid56-reunion.html?date=2003-09-02/" ;
try
{
// Create a reader on the HTML content
URL url = new URI(uriStr).toURL();
URLConnection conn = url.openConnection();
InputStreamReader rd = new InputStreamReader(conn.getInputStream());
// Parse the HTML
EditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
try
{
doc.putProperty("IgnoreCharsetDirective", new Boolean(true));
kit.read(rd, doc, 0);
}
catch (javax.swing.text.ChangedCharSetException e)
{
System.out.println(e.getCharSetSpec().substring(e.getCharSetSpec().indexOf("=" ) + 1).trim());
}
finally
{
// Find all the A elements in the HTML document
HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
try
{
SimpleAttributeSet s;
String link;
while (it.isValid())
{
s = (SimpleAttributeSet) it.getAttributes();
link = (String) s.getAttribute(HTML.Attribute.HREF);
if (link != null)
System.out.println (link);
it.next();
}
}catch (NullPointerException e) {}
}
}
catch (URISyntaxException e) {}
catch (BadLocationException e) {}
catch (IOException e){}
}
} |
Ce programme me donne tous les liens sauf le résultat du script suivant qui, manuellement, s'exécute dans le navigateur pour donner un tableau de liens
Code:
1 2 3 4 5 6 7 8 9 10 11 12
| <script>
ChangementTab("ongletReunion_PMU_152432_1");
</script>
.
.
.
.
.
function ChangementTab(IdChamp){
TabIdChamp = IdChamp.split("_");
xajax_call("ChangementTab",'mon_tableau_'+TabIdChamp[1]+'_'+TabIdChamp[2],TabIdChamp[3],TabIdChamp[2],TabIdChamp[1],'2001-05-15');
} |
Dans le code source (avec Mozilla Firefox), ces données s'affichent seulement quand on les sélectionne et qu'on clique sur "Code source de la sélection", sur "Code source" tout court, rien ne s'affiche ...
Un programme qui s'appelle wget (sous linux) ne fait pas mieux.
Comment faire pour récupérer ces données dans un flux ? :roll:
Je suis un novice en Ajax.
Merci d'avance. ;)
Comment accèder au contenu et aux attributs d'un Element ?
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:
Code:
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:
Code:
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.
Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
Voilà une éventuelle solution que j'ai pu trouver sur la toile, ici, mais que je n'ai pas su mettre en oeuvre:
Citation:
The short question is, can I prevent the parser from even trying to
: get the DTD?
Use a Schema to validate the document:
- Set validating to false
- Load a new schema into the DocumentBuilderFactory using SchemaFactory.newSchema(File)
This should stop the on-line request for a DTD and load a local file as the DTD.
Pourriez-vous me proposer une adaptation de cette solution à mon problème ?