Scala HTML解析器对象用法

时间:2012-07-10 18:02:10

标签: html parsing scala

我正在使用HTML解析器来解析HTML字符串:

import nu.validator.htmlparser.{sax,common}
import sax.HtmlParser
import common.XmlViolationPolicy

val source = Source.fromString(response)
val html = new models.HTML5Parser
val htmlObject = html.loadXML(source)

如何为对象中的特定元素提取值?我可以用这个来得到孩子和标签:

val child = htmlObject.child(1).label

但我不知道如何获得孩子的内容。另外,我不知道如何遍历子对象。

1 个答案:

答案 0 :(得分:3)

目前还不清楚你的HTML5Parser课程来自哪里,但我会假设它是this example中的那个(或类似的东西)。在这种情况下,您的htmlObject只是scala.xml.Node。首先进行一些设置:

val source = Source.fromString(
  "<html><head/><body><div class='main'><span>test</span></div></body></html>"
)

val htmlObject = html.loadXML(source)

现在您可以执行以下操作,例如:

scala> htmlObject.child(1).label
res0: String = body

scala> htmlObject.child(1).child(0).child(0).text
res1: String = test

scala> (htmlObject \\ "span").text
res2: String = test

scala> (htmlObject \ "body" \ "div" \ "span").text
res3: String = test

scala> (htmlObject \\ "div").head.attributes.asAttrMap
res4: Map[String,String] = Map(class -> main)

等等。