9

我有一个包含表格的 html 页面,我想以 C# windows 形式解析该表格

http://www.mufap.com.pk/payout-report.php?tab=01

这是我想解析的网页我试过

> Foreach(Htmlnode a in document.getelementbyname("tr"))
{
    richtextbox1.text=a.innertext;
}

我已经尝试过这样的事情,但它不会以表格形式给我,因为我只是打印所有 trs 所以请帮助我解决这个thanx对不起我的英语。

4

3 回答 3

51

使用HTML 敏捷包

WebClient webClient = new WebClient();
string page = webClient.DownloadString("http://www.mufap.com.pk/payout-report.php?tab=01");

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);

List<List<string>> table = doc.DocumentNode.SelectSingleNode("//table[@class='mydata']")
            .Descendants("tr")
            .Skip(1)
            .Where(tr=>tr.Elements("td").Count()>1)
            .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList())
            .ToList();
于 2012-10-22T06:13:52.147 回答
15

你的意思是这样的吗?

foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    ///This is the table.    
    foreach (HtmlNode row in table.SelectNodes("tr")) {
    ///This is the row.
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            ///This the cell.
        }
    }
}
于 2012-10-22T04:59:15.783 回答
2

迟到了,但是使用普通 C# 代码执行您要求的方法可能如下

/// <summary>
/// parses a table and returns a list containing all the data with columns separated by tabs
/// e.g.: records = getTable(doc, 0);
/// </summary>
/// <param name="doc">HtmlDocument to work with</param>
/// <param name="number">table index (base 0)</param>
/// <returns>list containing the table data</returns>
public List<string> getTableData(HtmlDocument doc, int number)
{
  HtmlElementCollection tables = doc.GetElementsByTagName("table");
  int idx=0;
  List<string> data = new List<string>();

  foreach (HtmlElement tbl in tables)
  {
    if (idx++ == number)
    {
      data = getTableData(tbl);
      break;
    }
  }
  return data;
}

/// <summary>
/// parses a table and returns a list containing all the data with columns separated by tabs
/// e.g.: records = getTable(getElement(doc, "table", "id", "table1"));
/// </summary>
/// <param name="tbl">HtmlElement table to work with</param>
/// <returns>list containing the table data</returns>
public List<string> getTableData(HtmlElement tbl)
{
  int nrec = 0;
  List<string> data = new List<string>();
  string rowBuff;

  HtmlElementCollection rows = tbl.GetElementsByTagName("tr");
  HtmlElementCollection cols;
  foreach (HtmlElement tr in rows)
  {
    cols = tr.GetElementsByTagName("td");
    nrec++;
    rowBuff = nrec.ToString();
    foreach (HtmlElement td in cols)
    {
      rowBuff += "\t" + WebUtility.HtmlDecode(td.InnerText);
    }
    data.Add(rowBuff);
  }

  return data;
}

以上将允许您通过使用页面内的表“索引”(对未命名的表有用)或通过将“表”HtmlElement 传递给函数(更快但仅对命名表有用)从表中提取数据;请注意,我选择返回“列表”作为结果,并使用制表符分隔各个列数据;您可以轻松更改代码以您喜欢的任何其他格式返回数据

于 2016-03-29T10:23:55.810 回答