HTML敏捷包

问题描述:

我想用html敏捷包解析html表。我只想从表中提取一些预定义的列数据。HTML敏捷包

但我是新来的解析和HTML敏捷包,我试过了,但我不知道如何使用HTML敏捷包为我的需要。

如果有人知道然后给我举例来说,如果可能的

编辑:

是否可以解析HTML表格一样,如果我们只想提取的决定列名数据?就像有4列名称,地址,phno一样,我只想提取姓名和地址数据。

+0

@Harikrishna - 你有一个表结构的小样本? – 2010-03-11 09:32:07

+0

有关使用html Agility pack从html数据中提取数据的更多信息:http://*.com/questions/2431652/html-agility-pack – Harikrishna 2010-03-13 10:09:07

在讨论论坛here中有一个例子。向下滚动一下以查看表格答案。我希望他们能提供更容易找到的更好的样本。

编辑: 要从特定列中提取数据,您必须首先找到与您想要的列对应的<th>标记并记住它们的索引。然后您需要为相同的索引找到<td>标签。假设你知道列的索引,你可以做这样的事情:

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml("http://somewhere.com"); 
HtmlNode table = doc.DocumentNode.SelectSingleNode("//table"); 
foreach (var row in table.SelectNodes("//tr")) 
{ 
    HtmlNode addressNode = row.SelectSingleNode("td[2]"); 
    //do something with address here 
    HtmlNode phoneNode = row.SelectSingleNode("td[5]"); 
    // do something with phone here 
} 

EDIT2: 如果你不知道列的索引,你可以做这样整个事情。我没有测试过这个。

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml("http://somewhere.com"); 
var tables = doc.DocumentNode.SelectNodes("//table"); 

foreach(var table in tables) 
{ 
    int addressIndex = -1; 
    int phoneIndex = -1; 
    var headers = table.SelectNodes("//th"); 
    for (int headerIndex = 0; headerIndex < headers.Count(); headerIndex++) 
    { 
     if (headers[headerIndex].InnerText == "address") 
     { 
      addressIndex = headerIndex; 
     } 
     else if (headers[headerIndex].InnerText == "phone") 
     { 
      phoneIndex = headerIndex; 
     } 
    } 

    if (addressIndex != -1 && phoneIndex != -1) 
    { 
     foreach (var row in table.SelectNodes("//tr")) 
     { 
      HtmlNode addressNode = row.SelectSingleNode("td[addressIndex]"); 
      //do something with address here 
      HtmlNode phoneNode = row.SelectSingleNode("td[phoneIndex]"); 
      // do something with phone here 
     } 
    } 
} 
+0

@Harikrishna - 它是每个表中的同一种数据吗?你想从所有表中提取相同的列吗?你只想找到一个特定的表?在这里帮我一把。我一直试图回答,然后提供更多信息。让我们了解所有的信息。 – 2010-03-11 10:04:40

+0

@Mike Two Sir ..好吧,对不起...就像在网页上有不止一个表格标签,但我想从只有一个表格中提取数据,这些表格有我们定义的列名称,如地址和电话号码。其他表标签是用于其他信息,而不是有用的。 – Harikrishna 2010-03-11 10:08:02

+0

@Mike Two Sir ..有很多网页有多个表格。而且我想从每个网页中提取只有一个表格的数据,这个表格的名字是电话号码和地址。 – Harikrishna 2010-03-11 10:09:57