C#用正则表达式 获取网页源代码标签的属性或值

本文介绍了使用C#进行网页爬取的方法,包括如何获取网页源代码、如何解析HTML标签来提取所需信息等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.有url获取到网页源代码:

using System.Web;
        using System.IO;
        using System.Net;
        private void GetHtmlinfo(string PageUrl)
        {
            WebRequest request = WebRequest.Create(PageUrl);
            WebResponse response = request.GetResponse();
            Stream resStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
            string htmlinfo = sr.ReadToEnd();
            resStream.Close();
            sr.Close();       
           
        }

 

 

2.获取标签中的值:

 

using System.Text.RegularExpressions;
         /// 获取字符中指定标签的值  
      /// </summary>  
        /// <param name="str">字符串</param>  
        /// <param name="title">标签</param>  
        /// <returns></returns>  
        public static string GetTitleContent(string str, string title1, string title2)  
        {  
            string tmpStr = string.Format("<{0}[^>]*?>(?<Text>[^<]*)</ {1}>", title1, title2); //获取<title>之间内容  
  
            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);  
  
            string result = TitleMatch.Groups["Text"].Value;  
            return result;  
        }

 

 

Example:
 HTML 源文件:<span class="t1_tx">现排名:<b class="color1">20</b>

 Parameter: title1 = @"span class=""t1_tx"">现排名:<b class=""color1""";

                  title2 - "b";

3.获取标签中的属性:

/// 获取字符中指定标签的值  
      /// </summary>  
        /// <param name="str">字符串</param>  
        /// <param name="title">标签</param>  
        /// <param name="attrib">属性名</param>  
        /// <returns>属性</returns>  
        public static string GetTitleContent(string str, string title,string attrib)  
        {  
  
            string tmpStr = string.Format("<{0}[^>]*?{1}=(['\"\"]?)(?<url>[^'\"\"\\s>]+)\\1[^>]*>", title, attrib); //获取<title>之间内容  
  
            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);  
  
            string result = TitleMatch.Groups["url"].Value;  
            return result;  
        }

 

转载于:https://www.cnblogs.com/zyh-club/p/5256702.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值