如何在C#中使用HtmlAgilityPack获取HTML元素的内容?

问题描述:

我想使用C#中的HTMLAgilityPack从HTML页面中获取有序列表的内容,我已经尝试了以下代码,但是,任何人都无法正常工作,我想传递html文本并获取其中的内容在html中找到的第一个有序列表

I want to get the contents of an ordered list from a HTML page using HTMLAgilityPack in C#, i have tried the following code but, this is not working can anyone help, i want to pass html text and get the contents of the first ordered list found in the html

private bool isOrderedList(HtmlNode node)
{
    if (node.NodeType == HtmlNodeType.Element)
    {
        if (node.Name.ToLower() == "ol")
            return true;
        else
            return false;
    }
    else
        return false;
}

public string GetOlList(string htmlText)
{
    string s="";
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(htmlText);
    HtmlNode nd = doc.DocumentNode;
    foreach (HtmlNode node in nd.ChildNodes)
    {
        if (isOrderedList(node))
        {
            s = node.WriteContentTo();
            break;
        }
        else if (node.HasChildNodes)
        {
            string sx= GetOlList(node.WriteTo());
            if (sx != "")
            {
                s = sx;
                break;
            }
        }
    }
    return s;
}

以下代码对我有用

public static string GetComments(string html)
{
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(html);
    string s = "";
    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//ol"))
    {
        s += node.OuterHtml;
    }

    return s;
}