C#获取html标签内容的方法

2022/3/21 11:57:39

本文主要是介绍C#获取html标签内容的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

C# 获取html标签内容的方法:

        /// <summary>
        /// 获取html网页标签内容
        /// 例如:<span class="index_infoItem__ESU0o"></span>
        /// </summary>
        /// <param name="html">html内容</param>
        /// <param name="tag">标签 例如:span</param>
        /// <param name="attribute">标签属性 例如:class</param>
        /// <param name="value">标签属性值 例如:index_infoItem__ESU0o</param>
        /// <returns></returns>
        public static string[] RegexHtmlToFormat(string html, string tag, string attribute, string value)
        {
            List<string> list = new List<string>();
            string regex_html = @"<"+ tag + ".*?"+ attribute + "=.*?"+ value + ".*?[^>]*?>.*?</" + tag + ">"; //定义html标签的正则表达式 
            Regex regex = new Regex(regex_html, RegexOptions.IgnoreCase);
            if (regex.IsMatch(html))
            {
                MatchCollection matchCollection = regex.Matches(html);
                foreach (Match match in matchCollection)
                {
                    var valueHtml = match.Value;
                    valueHtml = Regex.Replace(valueHtml, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);//去除html标签
                    list.Add(valueHtml);//获取到的
                }
            }
            return list.ToArray();
        }

 



这篇关于C#获取html标签内容的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程