HtmlAgilityPack行的Xpath语法

时间:2018-10-06 14:15:36

标签: vb.net html-agility-pack

我正在使用以下代码:

Dim cl As WebClient = New WebClient()
Dim html As String = cl.DownloadString(url)
Dim doc As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument()
doc.LoadHtml(html)

Dim table As HtmlNode = doc.DocumentNode.SelectSingleNode("//table[@class='table']")

For Each row As HtmlNode In table.SelectNodes(".//tr")
   Dim inner_text As String = row.InnerHtml.Trim()

Next

我的每一行的inner_text如下所示,具有不同的年份和数据:

       "<th scope="row">2015<!-- --> RG Journal Impact</th><td>6.33</td>"

每行都有一个th元素和一个td元素,我尝试了不同的方法来拉取值,但是我似乎无法通过循环列集合来一个接一个地拉它们。如何使用正确的Xpath语法仅提取th元素和td元素?

在我可以使用更好的代码之前,我将使用标准的解析函数:

Dim hname As String = row.InnerHtml.Trim()
Dim items() As String = hname.Split("</td>")
Dim year As String = items(1).Substring(items(1).IndexOf(">") + 1)

Dim value As String = items(4).Substring(items(4).IndexOf(">") + 1)
If value.ToLower.Contains("available") Then
    value = ""

End If

1 个答案:

答案 0 :(得分:1)

您可以继续查询行:

Option Infer On
Option Strict On

Imports HtmlAgilityPack

Module Module1

    Sub Main()
        Dim h = "<html><head><title></title></head><body>
<table class=""table"">
<tr><th scope=""row"">2015<!-- --> RG Journal Impact</th><td>6.33</td></tr>
<tr><th scope=""row"">2018 JIR</th><td>9.99</td></tr>
</table>
</body></html>"

        Dim doc = New HtmlAgilityPack.HtmlDocument()
        doc.LoadHtml(h)

        Dim table = doc.DocumentNode.SelectSingleNode("//table[@class='table']")

        For Each row In table.SelectNodes(".//tr")
            Dim yearData = row.SelectSingleNode(".//th").InnerText.Split(" "c)(0)
            Dim value = row.SelectSingleNode(".//td").InnerText
            Console.WriteLine($"Year: {yearData} Value: {value}")
        Next

        Console.ReadLine()

    End Sub

End Module

输出:

  

年份:2015年价值:6.33
  年份:2018价值:9.99