【问题标题】:Scrape Table from web page in c#从c#中的网页刮取表格
【发布时间】:2011-12-29 22:20:37
【问题描述】:

构建一个将网页上的 html 表格抓取到变量中的函数的最佳方法是什么。

我希望能够向它传递一些唯一标识符(例如表 ID 或其他东西),它会将所有数据返回到类似 DataTable 的东西中。

【问题讨论】:

  • 这并不像我想的那么简单,所以我想到了:mdukehall.wordpress.com/2011/10/12/…
  • @Michael 没有任何方法是万无一失的——即使使用第三方工具也是如此。 HTML 在关闭标签方面有非常宽松的标准,这意味着无法保证您的“XML”树将正确形成,因此大量的抓取可能很乏味并且容易试错。有时最好的方法是简单地在页面上的数据附近或附近找到一个静态元素,并围绕它运行你的逻辑。拆分、解析等,直到得到结果。

标签: c# html datatable scrape


【解决方案1】:

您可以使用HtmlAgilityPack解析HTML并提取表格数据。

随着 HAP 现在支持 Linq,您可以从以下内容开始:

HtmlDocument doc = ...
var myTable = doc.DocumentNode
                 .Descendants("table")
                 .Where(t =>t.Attributes["id"].Value == someTableId)
                 .FirstOrDefault();

if(myTable != null)
{
    ///further parsing here
}

【讨论】:

    【解决方案2】:
    string htmlCode = "";
    htmlCode = driver.PageSource.ToString();
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(htmlCode);
    
    var gvTender = doc.DocumentNode.Descendants("table")
                 .Where(table => table.Attributes.Contains("id"))
                 .FirstOrDefault(table => table.Attributes["id"].Value == "ctl00_cphContentArea_gvTenders");
    
    List<HtmlNode> rows = doc.DocumentNode.SelectNodes("//tr").Skip(10).ToList();
        foreach (var row in rows)
        {
            try
            {
                rowCount++;
                if (rowCount >= 16)
                    break;
    
                List<HtmlNode> cells = row.SelectNodes("th|td").ToList();
    
    
                string s1 = cells[0].InnerText.ToString().Replace("\r\n", "").Trim();
                string s2 = cells[1].InnerText.ToString().Replace("\r\n", "").Trim();
                string s3 = cells[2].InnerText.ToString();
                string s4 = cells[3].InnerText.ToString();
                string s5 = cells[4].InnerText.ToString();
                string s6 = cells[5].InnerText.ToString();
                string s7 = cells[6].InnerText.ToString();
                string s8 = cells[7].InnerText.ToString();
    
    
            }
            catch (Exception ex)
            {
    
            }
        }
        //Developed By -Ramdas Chavan(Datamatics)
    

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      相关资源
      最近更新 更多