Bonjour à tous,
Je fais du parsing de HTML avec Cobra en utilisant des recherches directement avec XPath.
Je m'appuie pour ce faire sur l'exemple donné dans leur site et repris ci-dessous:
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
| import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.util.logging.*;
import org.lobobrowser.html.UserAgentContext;
import org.lobobrowser.html.parser.*;
import org.lobobrowser.html.test.SimpleUserAgentContext;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ParseAnchorsTest {
private static final String TEST_URI = "http://lobobrowser.org";
public static void main(String[] args) throws Exception {
// Disable most Cobra logging.
Logger.getLogger("org.lobobrowser").setLevel(Level.WARNING);
UserAgentContext uacontext = new SimpleUserAgentContext();
// In this case we will use a standard XML document
// as opposed to Cobra's HTML DOM implementation.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
URL url = new URL(TEST_URI);
InputStream in = url.openConnection().getInputStream();
try {
Reader reader = new InputStreamReader(in, "ISO-8859-1");
Document document = builder.newDocument();
// Here is where we use Cobra's HTML parser.
HtmlParser parser = new HtmlParser(uacontext, document);
parser.parse(reader);
// Now we use XPath to locate "a" elements that are
// descendents of any "html" element.
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xpath.evaluate("//table/tr/td/child::text()", document, XPathConstants.NODESET);
...
} finally {
in.close();
}
}
} |
A la différence près que je cherche les tables et non les liens. J'ai donc créé une instruction XPath pour ça:
//table/tr/td/child::text()"
Le problème, c'est que si dans une des cellules de ma table j'ai du vide, l'instruction XPath ne me le remontera pas.
Avez-vous une solution...je cale !
Partager