Html avec cyberneko Parsing pour trouver un « div'-tag
Question
Je besoin d'un « div'-étiquette (identifiée par 'spécifique id') à partir d'un site html. Pour analyser la page J'utilise cyberneko.
def doc = new XmlParser( new org.cyberneko.html.parsers.SAXParser() ).parse(htmlFile)
divTag = doc.depthFirst().DIV.find{ it['@id'] == tagId }
Jusqu'à présent, aucun problème, mais à la fin je ne ai pas besoin XML, mais le contenu original de toute balise « div ». Malheureusement je ne peux pas comprendre comment faire ...
La solution
EDIT: En réponse à premier commentaire
.Cela fonctionne:
def html = """
<body>
<div id="breadcrumbs">
<b>
crumb1
</b>
</div>
</body>
"""
def doc = new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(html)
divTag = doc.BODY.DIV.find { it.@id == 'breadcrumbs' }
println "" << new groovy.xml.StreamingMarkupBuilder().bind {xml -> xml.mkp.yield divTag}
On dirait que cyberneko retournera un document HTML bien formé, que le balisage était d'origine. à savoir, la racine de doc sera un élément HTML, et il y aura aussi un élément HEAD. Neat.
Autres conseils
Ceci est un test simple basée sur la réponse de noé - il ne fonctionne malheureusement pas (encore): (
def html = """
<body>
<div id="breadcrumbs">
<b>
crumb1
</b>
</div>
</body>
"""
def doc = new XmlSlurper( new org.cyberneko.html.parsers.SAXParser() ).parseText(html)
println "document: $doc"
def htmlTag = doc.DIV.find {
println "-> $it"
it['@id'] == "breadcrumbs"
}
println htmlTag
assert htmlTag
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow