C#使用正則表達式抓取網(wǎng)站信息示例
本文實例講述了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#教程
本文標(biāo)題:C#使用正則表達式抓取網(wǎng)站信息示例
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/5982.html
您可能感興趣的文章
- 01-10C#使用Dispose模式實現(xiàn)手動對資源的釋放
- 01-10C#3.0使用EventLog類寫Windows事件日志的方法
- 01-10C#使用windows服務(wù)開啟應(yīng)用程序的方法
- 01-10c# ArrayList的使用方法小總結(jié)
- 01-10C#使用ADO.Net部件來訪問Access數(shù)據(jù)庫的方法
- 01-10C#使用Mutex簡單實現(xiàn)程序單實例運行的方法
- 01-10使用Nopcommerce為商城添加滿XX減XX優(yōu)惠券功能
- 01-10C#編程自學(xué)之運算符和表達式
- 01-10C#中yield用法使用說明
- 01-10C#編程和Visual Studio使用技巧(下)


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻 器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機閱讀
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10delphi制作wav文件的方法
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10C#中split用法實例總結(jié)
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-11ajax實現(xiàn)頁面的局部加載
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文