Html Agility Pack中的SelectNode始终为Null

时间:2014-10-27 08:29:31

标签: c# html-agility-pack

我尝试使用HtmlAgilityPack获取标记div的值,但我的结果始终为null。我不知道它为什么不能获得价值。

此代码:

HtmlWeb website = new HtmlWeb();
HtmlAgilityPack.HtmlDocument rootDocument = website.Load("http://blogviet.com.vn");
var value= rootDocument.DocumentNode.SelectNodes("//div");
if (value!= null)
{
    foreach (var tag in value)
    {
        if (tag.Attributes["class"] != null)
        {
            label2.Text += tag.Attributes["class"].Value + "\n";
        }
    }
}
else
{
    label2.Text = "null";
}

1 个答案:

答案 0 :(得分:0)

尝试Descendants

var divNodes = rootDocument.DocumentNode.Descendants("div");
var classNames =  divNodes.Select(d => d.GetAttributeValue("class","").Where(x => x != "");
label2.Text  = string.Join(Environment.NewLine, classNames);