首页 > 解决方案 > WebBrowser - 从没有 ID、没有 TagName、没有 Class 的通用表中获取/读取数据

问题描述

作为标题,我正在尝试从页面中的某些表中读取数据。
我经常使用WebBrowser1.Document.GetElementById很多类似的东西,但在这种情况下,我无法访问数据,因为在这个页面中,所有表都简单地由<table class="table">
以下是我要访问的内容定义:

<div class="col-md-6">
    <div class="panel panel-primary">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <h3 class="panel-title">Ryzen 3000 - Mainstream</h3>
        </div>

        <!-- Table -->
        <table class="table">
            <tbody>
                <tr>
                    <th>Ryzen 5 3500</th>
                    <td>3.6 - 4.1</td>
                </tr>
                <tr>
                    <th>Ryzen 5 3500X</th>
                    <td>3.6 - 4.1</td>
                </tr>
                <tr>
                    <th>Ryzen 5 3600</th>
                    <td>3.6 - 4.2</td>
                </tr>
                <tr>
                    <th>Ryzen 5 Pro 3600</th>
                    <td>3.6 - 4.2</td>
                </tr>
                <tr>
                    <th>Ryzen 5 3600X</th>
                    <td>3.8 - 4.4</td>
                </tr>
                <tr>
                    <th>Ryzen 5 3600XT</th>
                    <td>3.8 - 4.5</td>
                </tr>

            </tbody>
        </table>

    </div>
    <!--</panel>-->
</div>

我在网上搜索了很多,但我找不到有效的解决方案。有人有提示吗?

标签: vb.netvisual-studio

解决方案


我推荐你使用 HtmlAgilityPack 和Xpath解析公式。

示例代码:
查询特定th标签文本:

    Dim doc As HtmlAgilityPack.HtmlDocument
    Dim path As String = "https://www..."
    Dim web As New HtmlWeb
    doc = web.Load(path)
    Dim node As HtmlAgilityPack.HtmlNode
   'The text within the fourth <th></th>
    node = doc.DocumentNode.SelectNodes("//table[@class='table']//th")(3) 
    Dim st As String = node.InnerText  'Ryzen 5 Pro 3600

查询所有tr文本:

    Dim doc As HtmlAgilityPack.HtmlDocument
    Dim path As String = "https://www..."
    Dim web As New HtmlWeb
    doc = web.Load(path)
    Dim nodes As HtmlAgilityPack.HtmlNodeCollection
    nodes = doc.DocumentNode.SelectNodes("//table[@class='table']//tr")
    For Each node As HtmlNode In nodes
        RichTextBox1.AppendText(node.InnerText)
    Next

结果: 在此处输入图像描述


推荐阅读