使用LINQ和htmllagilitypack解析html表
本文关键字:html 解析 htmllagilitypack LINQ 使用 | 更新日期: 2023-09-27 18:13:05
我想解析日期,链接文本和链接href从表class='nice'在网页http://cslh.cz/delegace.html?id_season=2013
我已经创建了对象DelegationLink
public class DelegationLink
{
public string date { get; set; }
public string link { get; set; }
public string anchor { get; set; }
}
和LINQ一起创建List of DelegationLink
var parsedValues =
from table in htmlDoc.DocumentNode.SelectNodes("//table[@class='nice']")
from date in table.SelectNodes("tr//td")
from link in table.SelectNodes("tr//td//a")
.Where(x => x.Attributes.Contains("href"))
select new DelegationLink
{
date = date.InnerText,
link = link.Attributes["href"].Value,
anchortext = link.InnerText,
};
return parsedValues.ToList();
它只需要一个日期列,并将其与每行中的链接列相结合,但我只想简单地取表中的每一行,并从该行获取日期,href和hreftext。我是LINQ的新手,我用了4个小时的谷歌没有任何效果。谢谢你的帮助。
嗯,这很容易,你只需要在SelectNodes
函数调用中选择tr
,并稍微调整一下你的代码。像这样。
var parsedValues = htmlDoc.DocumentNode.SelectNodes("//table[@class='nice']/tr").Skip(1)
.Select(r =>
{
var linkNode = r.SelectSingleNode(".//a");
return new DelegationLink()
{
date = r.SelectSingleNode(".//td").InnerText,
link = linkNode.GetAttributeValue("href",""),
anchor = linkNode.InnerText,
};
}
);
return parsedValues.ToList();