程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類實例

C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類實例

編輯:C#入門知識

C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類實例。本站提示廣大學習愛好者:(C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類實例正文


C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類實例

作者:roucheng

這篇文章主要介紹了C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類,結合完整實例形式分析了C#正則網頁抓取類與使用技巧,需要的朋友可以參考下

本文實例講述了C#基於正則表達式實現獲取網頁中所有信息的網頁抓取類。分享給大家供大家參考,具體如下:

類的代碼:

using System;
using System.Data;
using System.Configuration;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI.MobileControls;
/// <summary>
/// 網頁類
/// </summary>
public class WebPage
{
    #region 私有成員
    private Uri m_uri;  //url
    private List<Link> m_links;  //此網頁上的鏈接
    private string m_title;    //標題
    private string m_html;     //HTML代碼
    private string m_outstr;    //網頁可輸出的純文本
    private bool m_good;      //網頁是否可用
    private int m_pagesize;    //網頁的大小
    private static Dictionary<string, CookieContainer> webcookies = new Dictionary<string, CookieContainer>();//存放所有網頁的Cookie
    #endregion
    #region 屬性
    /// <summary>
    /// 通過此屬性可獲得本網頁的網址,只讀
    /// </summary>
    public string URL
    {
      get
      {
        return m_uri.AbsoluteUri;
      }
    }
    /// <summary>
    /// 通過此屬性可獲得本網頁的標題,只讀
    /// </summary>
    public string Title
    {
      get
      {
        if (m_title == "")
        {
          Regex reg = new Regex(@"(?m)<title[^>]*>(?<title>(?:\w|\W)*?)</title[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
          Match mc = reg.Match(m_html);
          if (mc.Success)
            m_title = mc.Groups["title"].Value.Trim();
        }
        return m_title;
      }
    }
    public string M_html
    {
      get
      {
        if (m_html == null)
        {
          m_html = "";
        }
        return m_html;
      }
    }
    /// <summary>
    /// 此屬性獲得本網頁的所有鏈接信息,只讀
    /// </summary>
    public List<Link> Links
    {
      get
      {
        if (m_links.Count == 0) getLinks();
        return m_links;
      }
    }
    /// <summary>
    /// 此屬性返回本網頁的全部純文本信息,只讀
    /// </summary>
    public string Context
    {
      get
      {
        if (m_outstr == "") getContext(Int16.MaxValue);
        return m_outstr;
      }
    }
    /// <summary>
    /// 此屬性獲得本網頁的大小
    /// </summary>
    public int PageSize
    {
      get
      {
        return m_pagesize;
      }
    }
    /// <summary>
    /// 此屬性獲得本網頁的所有站內鏈接
    /// </summary>
    public List<Link> InsiteLinks
    {
      get
      {
        return getSpecialLinksByUrl("^http://" + m_uri.Host, Int16.MaxValue);
      }
    }
    /// <summary>
    /// 此屬性表示本網頁是否可用
    /// </summary>
    public bool IsGood
    {
      get
      {
        return m_good;
      }
    }
    /// <summary>
    /// 此屬性表示網頁的所在的網站
    /// </summary>
    public string Host
    {
      get
      {
        return m_uri.Host;
      }
    }
    #endregion
    /// <summary>
    /// 從HTML代碼中分析出鏈接信息
    /// </summary>
    /// <returns>List<Link></returns>
    private List<Link> getLinks()
    {
      if (m_links.Count == 0)
      {
        Regex[] regex = new Regex[2];
        regex[0] = new Regex(@"<a\shref\s*=""(?<URL>[^""]*).*?>(?<title>[^<]*)</a>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
        regex[1] = new Regex("<[i]*frame[^><]+src=(\"|')?(?<url>([^>\"'\\s)])+)(\"|')?[^>]*>", RegexOptions.IgnoreCase);
        for (int i = 0; i < 2; i++)
        {
          Match match = regex[i].Match(m_html);
          while (match.Success)
          {
            try
            {
              string url = HttpUtility.UrlDecode(new Uri(m_uri, match.Groups["URL"].Value).AbsoluteUri);
              string text = "";
              if (i == 0) text = new Regex("(<[^>]+>)|(\\s)|( )|&|\"", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(match.Groups["text"].Value, "");
              Link link = new Link();
              link.Text = text;
              link.NavigateUrl = url;
              m_links.Add(link);
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); };
            match = match.NextMatch();
          }
        }
      }
      return m_links;
    }
    /// <summary>
    /// 此私有方法從一段HTML文本中提取出一定字數的純文本
    /// </summary>
    /// <param name="instr">HTML代碼</param>
    /// <param name="firstN">提取從頭數多少個字</param>
    /// <param name="withLink">是否要鏈接裡面的字</param>
    /// <returns>純文本</returns>
    private string getFirstNchar(string instr, int firstN, bool withLink)
    {
      if (m_outstr == "")
      {
        m_outstr = instr.Clone() as string;
        m_outstr = new Regex(@"(?m)<script[^>]*>(\w|\W)*?</script[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, "");
        m_outstr = new Regex(@"(?m)<style[^>]*>(\w|\W)*?</style[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, "");
        m_outstr = new Regex(@"(?m)<select[^>]*>(\w|\W)*?</select[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, "");
        if (!withLink) m_outstr = new Regex(@"(?m)<a[^>]*>(\w|\W)*?</a[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, "");
        Regex objReg = new System.Text.RegularExpressions.Regex("(<[^>]+?>)| ", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        m_outstr = objReg.Replace(m_outstr, "");
        Regex objReg2 = new System.Text.RegularExpressions.Regex("(\\s)+", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        m_outstr = objReg2.Replace(m_outstr, " ");
      }
      return m_outstr.Length > firstN ? m_outstr.Substring(0, firstN) : m_outstr;
    }
    #region 公有文法
    /// <summary>
    /// 此公有方法提取網頁中一定字數的純文本,包括鏈接文字
    /// </summary>
    /// <param name="firstN">字數</param>
    /// <returns></returns>
    public string getContext(int firstN)
    {
      return getFirstNchar(m_html, firstN, true);
    }
    /// <summary>
    /// 此公有方法從本網頁的鏈接中提取一定數量的鏈接,該鏈接的URL滿足某正則式
    /// </summary>
    /// <param name="pattern">正則式</param>
    /// <param name="count">返回的鏈接的個數</param>
    /// <returns>List<Link></returns>
    public List<Link> getSpecialLinksByUrl(string pattern, int count)
    {
      if (m_links.Count == 0) getLinks();
      List<Link> SpecialLinks = new List<Link>();
      List<Link>.Enumerator i;
      i = m_links.GetEnumerator();
      int cnt = 0;
      while (i.MoveNext() && cnt < count)
      {
        if (new Regex(pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase).Match(i.Current.NavigateUrl).Success)
        {
          SpecialLinks.Add(i.Current);
          cnt++;
        }
      }
      return SpecialLinks;
    }
    /// <summary>
    /// 此公有方法從本網頁的鏈接中提取一定數量的鏈接,該鏈接的文字滿足某正則式
    /// </summary>
    /// <param name="pattern">正則式</param>
    /// <param name="count">返回的鏈接的個數</param>
    /// <returns>List<Link></returns>
    public List<Link> getSpecialLinksByText(string pattern, int count)
    {
      if (m_links.Count == 0) getLinks();
      List<Link> SpecialLinks = new List<Link>();
      List<Link>.Enumerator i;
      i = m_links.GetEnumerator();
      int cnt = 0;
      while (i.MoveNext() && cnt < count)
      {
        if (new Regex(pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase).Match(i.Current.Text).Success)
        {
          SpecialLinks.Add(i.Current);
          cnt++;
        }
      }
      return SpecialLinks;
    }
    /// <summary>
    /// 這公有方法提取本網頁的純文本中滿足某正則式的文字 by 何問起
    /// </summary>
    /// <param name="pattern">正則式</param>
    /// <returns>返回文字</returns>
    public string getSpecialWords(string pattern)
    {
      if (m_outstr == "") getContext(Int16.MaxValue);
      Regex regex = new Regex(pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);
      Match mc = regex.Match(m_outstr);
      if (mc.Success)
        return mc.Groups[1].Value;
      return string.Empty;
    }
    #endregion
    #region 構造函數
    private void Init(string _url)
    {
      try
      {
        m_uri = new Uri(_url);
        m_links = new List<Link>();
        m_html = "";
        m_outstr = "";
        m_title = "";
        m_good = true;
        if (_url.EndsWith(".rar") || _url.EndsWith(".dat") || _url.EndsWith(".msi"))
        {
          m_good = false;
          return;
        }
        HttpWebRequest rqst = (HttpWebRequest)WebRequest.Create(m_uri);
        rqst.AllowAutoRedirect = true;
        rqst.MaximumAutomaticRedirections = 3;
        rqst.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
        rqst.KeepAlive = true;
        rqst.Timeout = 10000;
        lock (WebPage.webcookies)
        {
          if (WebPage.webcookies.ContainsKey(m_uri.Host))
            rqst.CookieContainer = WebPage.webcookies[m_uri.Host];
          else
          {
            CookieContainer cc = new CookieContainer();
            WebPage.webcookies[m_uri.Host] = cc;
            rqst.CookieContainer = cc;
          }
        }
        HttpWebResponse rsps = (HttpWebResponse)rqst.GetResponse();
        Stream sm = rsps.GetResponseStream();
        if (!rsps.ContentType.ToLower().StartsWith("text/") || rsps.ContentLength > 1 << 22)
        {
          rsps.Close();
          m_good = false;
          return;
        }
        Encoding cding = System.Text.Encoding.Default;
        string contenttype = rsps.ContentType.ToLower();
        int ix = contenttype.IndexOf("charset=");
        if (ix != -1)
        {
          try
          {
            cding = System.Text.Encoding.GetEncoding(rsps.ContentType.Substring(ix + "charset".Length + 1));
          }
          catch
          {
            cding = Encoding.Default;
          }
          //該處視情況而定 有的需要解碼
          //m_html = HttpUtility.HtmlDecode(new StreamReader(sm, cding).ReadToEnd());
          m_html = new StreamReader(sm, cding).ReadToEnd();
        }
        else
        {
         //該處視情況而定 有的需要解碼
          //m_html = HttpUtility.HtmlDecode(new StreamReader(sm, cding).ReadToEnd());
          m_html = new StreamReader(sm, cding).ReadToEnd();
          Regex regex = new Regex("charset=(?<cding>[^=]+)?\"", RegexOptions.IgnoreCase);
          string strcding = regex.Match(m_html).Groups["cding"].Value;
          try
          {
            cding = Encoding.GetEncoding(strcding);
          }
          catch
          {
            cding = Encoding.Default;
          }
          byte[] bytes = Encoding.Default.GetBytes(m_html.ToCharArray());
          m_html = cding.GetString(bytes);
          if (m_html.Split('?').Length > 100)
          {
            m_html = Encoding.Default.GetString(bytes);
          }
        }
        m_pagesize = m_html.Length;
        m_uri = rsps.ResponseUri;
        rsps.Close();
      }
      catch (Exception ex)
      {
      }
    }
    public WebPage(string _url)
    {
      string uurl = "";
      try
      {
        uurl = Uri.UnescapeDataString(_url);
        _url = uurl;
      }
      catch { };
      Init(_url);
    }
    #endregion
}

調用:

WebPage webInfo = new WebPage("http://hovertree.net/");
webInfo.Context;//不包含html標簽的所有內容
webInfo.M_html;//包含html標簽的內容 by 何問起

PS:這裡再為大家提供2款非常方便的正則表達式工具供大家參考使用:

JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript

正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg

更多關於C#相關內容感興趣的讀者可查看本站專題:《C#正則表達式用法總結》、《C#編碼操作技巧總結》、《C#中XML文件操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結》、《C#數據結構與算法教程》、《C#面向對象程序設計入門教程》及《C#程序設計之線程使用技巧總結》

希望本文所述對大家C#程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved