欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁 > 軟件編程 > C#教程 >

C#使用正則表達式抓取網(wǎng)站信息示例

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊: 次

本文實例講述了C#使用正則表達式抓取網(wǎng)站信息的方法。分享給大家供大家參考,具體如下:

這里以抓取京東商城商品詳情為例。

1、創(chuàng)建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 = "";   //商品關(guān)鍵ID
        string title = "";      //標(biāo)題
        decimal price = 0;      //價格
        string picName = "";     //圖片
        //提取商品關(guān)鍵ID
        pattern = @"http://item.jd.com/(?<Object>\d+).html";
        sourceWebID = WebHandler.GetRegexText(url, pattern);
        //提取標(biāo)題
        pattern = @"<div.*id=\""name\"".*>[\s\S]*<h1>(?<Object>.*?)</h1>";
        title = WebHandler.GetRegexText(htmlStr, pattern);
        //提取圖片
        int begin = htmlStr.IndexOf("<div id=\"spec-n1\"");
        int end = htmlStr.IndexOf("</div>", 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、創(chuàng)建WebHandler.cs公共方法類

/// <summary>
/// 公共方法類
/// </summary>
public class WebHandler
{
  /// <summary>
  /// 獲取網(wǎng)頁的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(); //創(chuàng)建WebResponse對象
        Stream datastream = response.GetResponseStream(); //創(chuàng)建流對象
        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(); //讀取數(shù)據(jù)
        reader.Close();
        datastream.Close();
        response.Close();
      }
    }
    catch { }
    return htmlStr;
  }
  /// <summary>
  /// 獲取正則表達式中的關(guān)鍵字
  /// </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;
  }
}

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

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

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

更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#正則表達式用法總結(jié)》、《C#編碼操作技巧總結(jié)》、《C#中XML文件操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》及《C#程序設(shè)計之線程使用技巧總結(jié)》

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

上一篇:SuperSocket入門--Telnet服務(wù)器和客戶端請求處理

欄    目:C#教程

下一篇:Winform中進行MD5加密的實例

本文標(biāo)題:C#使用正則表達式抓取網(wǎng)站信息示例

本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/5982.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有