如何在C#中使用HtmlAgilityPack获取HTML元素的内容? [英] How to get the contents of a HTML element using HtmlAgilityPack in C#?

查看:111
本文介绍了如何在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;
}

这篇关于如何在C#中使用HtmlAgilityPack获取HTML元素的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆