在AngleSharp c#或vb中循环父节点内部的子节点



我正在使用AngleSharp来解析html字符串。

我可以让它解析一个包含一些我想提取的内部divs/h3标签的outdiv,但我不知道如何进行

到目前为止我有

Dim outer_linq = document.All.Where(Function(w) w.LocalName = "div" AndAlso w.ClassList.Contains("the-product"))
For Each item In outer_linq
If item.LocalName = "h1" AndAlso item.ClassList.Contains("the-product-title") Then
' Found h1.the-product-title, so do something with it here
End If
If item.LocalName = "div" AndAlso item.ClassList.Contains("price") Then
' Found div.price, so do something with it here
End If
Next

所以它是在寻找div.the-product内部的一切,但我如何查看div.the/product,并获得div.the-product中每组的h1.the-process-title和div.price?

有几个div.the-product,每个都包含一个h1.the-proproduct-title和div.price

使用VB但使用c#也可以。

如果有人能帮忙,谢谢。

虽然您可以利用AngleSharp中的LINQ等技术,但我们鼓励每个人尽可能多地使用DOM(文档对象模型(。

不应该使用document.All.Where,而应该只使用document.QuerySelectorAll:

document.QuerySelectorAll("div.the-product")

您甚至可以直接执行嵌套,例如

document.QuerySelectorAll("div.the-product h1.the-product-title")

将找到具有the-product-title类并且在具有the-product类的div元素的(后代(之下的所有h1元素。如果您想要子代(而不是子代(,只需使用>运算符:

document.QuerySelectorAll("div.the-product > h1.the-product-title")

上面的代码错误的地方是您再次使用item。所有检索到的项实际上都已经是div元素(这就是您迭代的内容(,所以它们也不能是h1元素。

上面代码的一个简单修复方法是,你使用上面写的外循环,但在内部你会写,例如

Dim allInnerH1 = item.QuerySelectorAll("h1.the-product-title")
Dim allInnerPrices = item.QuerySelectorAll("div.price")

最新更新