F#.Data HTML 解析器从节点中提取字符串
F#.Data HTML Parser Extracting Strings From Nodes
我正在尝试使用 FSharp.Data 的 HTML 解析器从 href 属性中提取字符串链接列表。
我可以将链接打印到控制台,但是,我很难将它们放入列表中。
打印所需链接的代码的工作片段:
let results = HtmlDocument.Load(myUrl)
let links =
results.Descendants("td")
|> Seq.filter (fun x -> x.HasClass("pagenav"))
|> Seq.map (fun x -> x.Elements("a"))
|> Seq.iter (fun x -> x |> Seq.iter (fun y -> y.AttributeValue("href") |> printf "%A"))
如何将这些字符串存储到变量链接中而不是打印出来?
干杯,
在最后一行,你得到了一系列序列 - 对于每个 td.pagenav
你有一堆 <a>
,每个都有一个 href
。这就是为什么您必须有两个嵌套的 Seq.iter
s - 首先迭代外部序列,然后在每次迭代中迭代内部序列。
要展平一系列序列,请使用 Seq.collect
。此外,要将序列转换为列表,请使用 Seq.toList
或 List.ofSeq
(它们是等效的):
let a = [ [1;2;3]; [4;5;6] ]
let b = a |> Seq.collect id |> Seq.toList
> val b : int list = [1; 2; 3; 4; 5; 6]
将此应用于您的代码:
let links =
results.Descendants("td")
|> Seq.filter (fun x -> x.HasClass("pagenav"))
|> Seq.map (fun x -> x.Elements("a"))
|> Seq.collect (fun x -> x |> Seq.map (fun y -> y.AttributeValue("href")))
|> Seq.toList
或者您可以通过在您第一次遇到嵌套序列的地方应用 Seq.collect
使其更清晰:
let links =
results.Descendants("td")
|> Seq.filter (fun x -> x.HasClass("pagenav"))
|> Seq.collect (fun x -> x.Elements("a"))
|> Seq.map (fun y -> y.AttributeValue("href"))
|> Seq.toList
也就是说,我宁愿将其重写为列表理解。看起来更干净:
let links = [ for td in results.Descendants "td" do
if td.HasClass "pagenav" then
for a in td.Elements "a" ->
a.AttributeValue "href"
]
我正在尝试使用 FSharp.Data 的 HTML 解析器从 href 属性中提取字符串链接列表。
我可以将链接打印到控制台,但是,我很难将它们放入列表中。
打印所需链接的代码的工作片段:
let results = HtmlDocument.Load(myUrl)
let links =
results.Descendants("td")
|> Seq.filter (fun x -> x.HasClass("pagenav"))
|> Seq.map (fun x -> x.Elements("a"))
|> Seq.iter (fun x -> x |> Seq.iter (fun y -> y.AttributeValue("href") |> printf "%A"))
如何将这些字符串存储到变量链接中而不是打印出来?
干杯,
在最后一行,你得到了一系列序列 - 对于每个 td.pagenav
你有一堆 <a>
,每个都有一个 href
。这就是为什么您必须有两个嵌套的 Seq.iter
s - 首先迭代外部序列,然后在每次迭代中迭代内部序列。
要展平一系列序列,请使用 Seq.collect
。此外,要将序列转换为列表,请使用 Seq.toList
或 List.ofSeq
(它们是等效的):
let a = [ [1;2;3]; [4;5;6] ]
let b = a |> Seq.collect id |> Seq.toList
> val b : int list = [1; 2; 3; 4; 5; 6]
将此应用于您的代码:
let links =
results.Descendants("td")
|> Seq.filter (fun x -> x.HasClass("pagenav"))
|> Seq.map (fun x -> x.Elements("a"))
|> Seq.collect (fun x -> x |> Seq.map (fun y -> y.AttributeValue("href")))
|> Seq.toList
或者您可以通过在您第一次遇到嵌套序列的地方应用 Seq.collect
使其更清晰:
let links =
results.Descendants("td")
|> Seq.filter (fun x -> x.HasClass("pagenav"))
|> Seq.collect (fun x -> x.Elements("a"))
|> Seq.map (fun y -> y.AttributeValue("href"))
|> Seq.toList
也就是说,我宁愿将其重写为列表理解。看起来更干净:
let links = [ for td in results.Descendants "td" do
if td.HasClass "pagenav" then
for a in td.Elements "a" ->
a.AttributeValue "href"
]