【发布时间】:2020-03-20 16:28:15
【问题描述】:
我想写一个函数让我从这个 html 中获取信息:
<div>
<h1>Some header.</h1>
<ul>
<li>
<p>Hello world!</p>
</li>
<li>
<p>What is going on? <a href="http://example.com">This is a link</a>.</p>
</li>
</ul>
</div>
到这个字符串:
一些标题。你好世界!到底是怎么回事?这是一个链接。
换句话说:我想让这个测试通过:
let testInput: string = """
<div>
<h1>Some header.</h1>
<ul>
<li>
<p>Hello world!</p>
</li>
<li>
<p>What is going on? <a href="http://example.com">This is a link</a>.</p>
</li>
</ul>
</div>
"""
let getContentsFromHtmlDocument (doc: HtmlDocument) =
let getInner (node: HtmlNode): string =
// How can I traverse this tree?
""
let result =
doc.Descendants ["h1"; "p"; "a"]
|> Seq.map getInner
|> List.ofSeq
|> List.fold (+) ""
result
[<Test>]
let Test1 () =
let htmlDoc: HtmlDocument = HtmlDocument.Parse(testInput)
let res = getContentsFromHtmlDocument htmlDoc
Assert.AreEqual("Some header. Hello world! What is going on? This is a link.", res)
但我无法确定如何遍历树。任何帮助,将不胜感激!谢谢。
【问题讨论】: