首页 文章

使用HtmlAgilityPack解析innerHTML

提问于
浏览
-2

只是想弄清楚如何解析已经解析过的信息中的信息 .

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div [@class=\"result-link\"]"))
{
    if (node == null)
        Console.WriteLine("debug");
    else
    {
        //string h_url = node.Attributes["a"].Value;
        Console.WriteLine(node.InnerHtml);
    }
}

因此,您可以看到我正在尝试使用'string h_url'声明 . 在“result-link”div类中,有一个href属性,我试图获取href值 . 所以链接基本上 .

似乎无法弄明白 . 我尝试过使用Attributes数组:

string h_url = node.Attributes["//a[@href].Value;

没有运气 .

1 回答

  • 2

    您可以使用XPath选择与当前节点相关的元素:

    HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='result-link']");
    if (nodes != null)
    {
        foreach (HtmlNode node in nodes)
        {
            HtmlNode a = node.SelectSingleNode("a[@href]");
            if (a != null)
            {
                // use  a.Attributes["href"];
            }
    
            // etc...
        }
    }
    

相关问题