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();
        }

 

posted on 2022-03-21 11:20  £冷☆月№  阅读(1420)  评论(0编辑  收藏  举报