欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年01月23日 11:35:20   作者:pan_junbiao  
這篇文章主要介紹了C#使用正則表達(dá)式抓取網(wǎng)站信息,結(jié)合實(shí)例形式分析了C#針對(duì)網(wǎng)頁(yè)信息的正則抓取操作相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

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

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

1、創(chuàng)建JdRobber.cs程序類(lèi)

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 = "";     //正則表達(dá)式
        string sourceWebID = "";   //商品關(guān)鍵ID
        string title = "";      //標(biāo)題
        decimal price = 0;      //價(jià)格
        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);
        }
        //提取價(jià)格
        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("商品名稱(chēng):{0}", title);
        Console.WriteLine("圖片:{0}", picName);
        Console.WriteLine("價(jià)格:{0}", price);
      }
    }
  }
}

2、創(chuàng)建WebHandler.cs公共方法類(lèi)

/// <summary>
/// 公共方法類(lèi)
/// </summary>
public class WebHandler
{
  /// <summary>
  /// 獲取網(wǎng)頁(yè)的HTML碼
  /// </summary>
  /// <param name="url">鏈接地址</param>
  /// <param name="encoding">編碼類(lèi)型</param>
  /// <returns></returns>
  public static string GetHtmlStr(string url, string encoding)
  {
    string htmlStr = "";
    try
    {
      if (!String.IsNullOrEmpty(url))
      {
        WebRequest request = WebRequest.Create(url); //實(shí)例化WebRequest對(duì)象
        WebResponse response = request.GetResponse(); //創(chuàng)建WebResponse對(duì)象
        Stream datastream = response.GetResponseStream(); //創(chuàng)建流對(duì)象
        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>
  /// 獲取正則表達(dá)式中的關(guān)鍵字
  /// </summary>
  /// <param name="input">文本</param>
  /// <param name="pattern">表達(dá)式</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>
  /// 返回有效價(jià)格
  /// </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款非常方便的正則表達(dá)式工具供大家參考使用:

JavaScript正則表達(dá)式在線測(cè)試工具:
http://tools.jb51.net/regex/javascript

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

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

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

相關(guān)文章

最新評(píng)論