我想使用 html 敏捷包解析 html 表。我只想从表中提取一些预定义的列数据。
但我是解析和 html 敏捷包的新手,我已经尝试过,但我不知道如何使用 html 敏捷包来满足我的需要。
如果有人知道,请尽可能给我一个例子
编辑 :
如果我们只想提取决定的列名的数据,是否可以解析 html 表?就像有 4 列名称、地址、phno 一样,我只想提取名称和地址数据。
我想使用 html 敏捷包解析 html 表。我只想从表中提取一些预定义的列数据。
但我是解析和 html 敏捷包的新手,我已经尝试过,但我不知道如何使用 html 敏捷包来满足我的需要。
如果有人知道,请尽可能给我一个例子
编辑 :
如果我们只想提取决定的列名的数据,是否可以解析 html 表?就像有 4 列名称、地址、phno 一样,我只想提取名称和地址数据。
在此处的讨论论坛中有一个示例。向下滚动一点以查看表格答案。我真希望他们能提供更容易找到的更好的样品。
编辑:要从特定列中提取数据,您必须首先找到与<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
}
}
}