首頁 後端開發 C#.Net教程 C#如何使用正規表示式抓取網站資訊的程式碼案例

C#如何使用正規表示式抓取網站資訊的程式碼案例

Mar 27, 2017 am 11:47 AM
c# 正規表示式

這篇文章主要介紹了C#使用正規表達式抓取網站資訊,結合實例形式分析了C#針對網頁資訊的正則抓取操作相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了C#使用正規表示式抓取網站資訊的方法。 ##1、建立JdRobber.cs程式類別

public class JdRobber
{
  /// <summary>
  /// 判断是否京东链接
  /// </summary>
  /// <param name="param"></param>
  /// <returns></returns>
  public bool ValidationUrl(string url)
  {
    bool result = false;
    if (!String.IsNullOrEmpty(url))
    {
      Regex regex = new Regex(@"^http://item.jd.com/\d+.html$");
      Match match = regex.Match(url);
      if (match.Success)
      {
        result = true;
      }
    }
    return result;
  }
  /// <summary>
  /// 抓取京东信息
  /// </summary>
  /// <param name="param"></param>
  /// <returns></returns>
  public void GetInfo(string url)
  {
    if (ValidationUrl(url))
    {
      string htmlStr = WebHandler.GetHtmlStr(url, "Default");
      if (!String.IsNullOrEmpty(htmlStr))
      {
        string pattern = "";     //正则表达式
        string sourceWebID = "";   //商品关键ID
        string title = "";      //标题
        decimal price = 0;      //价格
        string picName = "";     //图片
        //提取商品关键ID
        pattern = @"http://item.jd.com/(?<Object>\d+).html";
        sourceWebID = WebHandler.GetRegexText(url, pattern);
        //提取标题
        pattern = @"<p.*id=\""name\"".*>[\s\S]*<h1>(?<Object>.*?)</h1>";
        title = WebHandler.GetRegexText(htmlStr, pattern);
        //提取图片
        int begin = htmlStr.IndexOf("<p id=\"spec-n1\"");
        int end = htmlStr.IndexOf("</p>", begin + 1);
        if (begin > 0 && end > 0)
        {
          string subPicHtml = htmlStr.Substring(begin, end - begin);
          pattern = @"<img.*src=\""(?<Object>.*?)\"".*/>";
          picName = WebHandler.GetRegexText(subPicHtml, pattern);
        }
        //提取价格
        if (sourceWebID != "")
        {
          string priceUrl = @"http://p.3.cn/prices/get?skuid=J_" + sourceWebID + "&type=1";
          string priceJson = WebHandler.GetHtmlStr(priceUrl, "Default");
          pattern = @"\""p\"":\""(?<Object>\d+(\.\d{1,2})?)\""";
          price = WebHandler.GetValidPrice(WebHandler.GetRegexText(priceJson, pattern));
        }
        Console.WriteLine("商品名称:{0}", title);
        Console.WriteLine("图片:{0}", picName);
        Console.WriteLine("价格:{0}", price);
      }
    }
  }
}
登入後複製

2、建立WebHandler.cs公共方法類別

/// <summary>
/// 公共方法类
/// </summary>
public class WebHandler
{
  /// <summary>
  /// 获取网页的HTML码
  /// </summary>
  /// <param name="url">链接地址</param>
  /// <param name="encoding">编码类型</param>
  /// <returns></returns>
  public static string GetHtmlStr(string url, string encoding)
  {
    string htmlStr = "";
    try
    {
      if (!String.IsNullOrEmpty(url))
      {
        WebRequest request = WebRequest.Create(url); //实例化WebRequest对象
        WebResponse response = request.GetResponse(); //创建WebResponse对象
        Stream datastream = response.GetResponseStream(); //创建流对象
        Encoding ec = Encoding.Default;
        if (encoding == "UTF8")
        {
          ec = Encoding.UTF8;
        }
        else if (encoding == "Default")
        {
          ec = Encoding.Default;
        }
        StreamReader reader = new StreamReader(datastream, ec);
        htmlStr = reader.ReadToEnd(); //读取数据
        reader.Close();
        datastream.Close();
        response.Close();
      }
    }
    catch { }
    return htmlStr;
  }
  /// <summary>
  /// 获取正则表达式中的关键字
  /// </summary>
  /// <param name="input">文本</param>
  /// <param name="pattern">表达式</param>
  /// <returns></returns>
  public static string GetRegexText(string input, string pattern)
  {
    string result = "";
    if (!String.IsNullOrEmpty(input) && !String.IsNullOrEmpty(pattern))
    {
      Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
      Match match = regex.Match(input);
      if (match.Success)
      {
        result = match.Groups["Object"].Value;
      }
    }
    return result;
  }
  /// <summary>
  /// 返回有效价格
  /// </summary>
  /// <param name="strPrice"></param>
  /// <returns></returns>
  public static decimal GetValidPrice(string strPrice)
  {
    decimal price = 0;
    try
    {
      if (!String.IsNullOrEmpty(strPrice))
      {
        Regex regex = new Regex(@"^\d+(\.\d{1,2})?$", RegexOptions.IgnoreCase);
        Match match = regex.Match(strPrice);
        if (match.Success)
        {
          price = decimal.Parse(strPrice);
        }
      }
    }
    catch { }
    return price;
  }
}

以上是C#如何使用正規表示式抓取網站資訊的程式碼案例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

使用 C# 的活動目錄 使用 C# 的活動目錄 Sep 03, 2024 pm 03:33 PM

使用 C# 的 Active Directory 指南。在這裡,我們討論 Active Directory 在 C# 中的介紹和工作原理以及語法和範例。

C# 中的隨機數產生器 C# 中的隨機數產生器 Sep 03, 2024 pm 03:34 PM

C# 隨機數產生器指南。在這裡,我們討論隨機數產生器的工作原理、偽隨機數和安全數的概念。

C# 序列化 C# 序列化 Sep 03, 2024 pm 03:30 PM

C# 序列化指南。這裡我們分別討論C#序列化物件的介紹、步驟、工作原理和範例。

C# 資料網格視圖 C# 資料網格視圖 Sep 03, 2024 pm 03:32 PM

C# 資料網格視圖指南。在這裡,我們討論如何從 SQL 資料庫或 Excel 檔案載入和匯出資料網格視圖的範例。

C# 中的模式 C# 中的模式 Sep 03, 2024 pm 03:33 PM

C# 模式指南。在這裡,我們討論 C# 中模式的介紹和前 3 種類型,以及其範例和程式碼實作。

C# 中的質數 C# 中的質數 Sep 03, 2024 pm 03:35 PM

C# 質數指南。這裡我們討論c#中素數的介紹和範例以及程式碼實作。

C# 中的階乘 C# 中的階乘 Sep 03, 2024 pm 03:34 PM

C# 階乘指南。這裡我們討論 C# 中階乘的介紹以及不同的範例和程式碼實作。

c#多線程和異步的區別 c#多線程和異步的區別 Apr 03, 2025 pm 02:57 PM

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。

See all articles