HtmlAgilityPack 行的 Xpath 语法

Xpath syntax for HtmlAgilityPack row

我正在使用以下代码:

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 元素,我尝试了不同的方法来提取值,但我似乎无法通过循环列来一个接一个地提取它们collection。如何使用正确的 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

您可以继续查询行:

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

输出:

Year: 2015 Value: 6.33
Year: 2018 Value: 9.99