C#使用正則表達(dá)式抓取網(wǎng)站信息示例
本文實(shí)例講述了C#使用正則表達(dá)式抓取網(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 = ""; //正則表達(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("商品名稱:{0}", title);
Console.WriteLine("圖片:{0}", picName);
Console.WriteLine("價(jià)格:{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); //實(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á)式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#正則表達(dá)式用法總結(jié)》、《C#編碼操作技巧總結(jié)》、《C#中XML文件操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》及《C#程序設(shè)計(jì)之線程使用技巧總結(jié)》
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C#項(xiàng)目中跨文件調(diào)用公共類的實(shí)例方法
在本篇文章里小編給大家整理的是關(guān)于C#項(xiàng)目中如何跨文件調(diào)用公共類的知識(shí)點(diǎn)內(nèi)容,需要的朋友們學(xué)習(xí)下。2019-08-08
C#實(shí)現(xiàn)Excel動(dòng)態(tài)生成PivotTable
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)Excel動(dòng)態(tài)生成PivotTable的相關(guān)方法,感興趣的小伙伴們可以參考一下2016-04-04
C#使用LINQ中Enumerable類方法的延遲與立即執(zhí)行的控制
這篇文章主要介紹了C#的LINQ查詢中Enumerable類方法的延遲與立即執(zhí)行,LINQ語言集成查詢可以讓C#和VB以查詢數(shù)據(jù)庫相同的方式操作內(nèi)存數(shù)據(jù),需要的朋友可以參考下2016-03-03
c#使用IAsyncEnumerable實(shí)現(xiàn)流式分段傳輸
這篇文章主要為大家詳細(xì)介紹了c#如何使用IAsyncEnumerable實(shí)現(xiàn)流式分段傳輸,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10
C# 表達(dá)式樹Expression Trees的知識(shí)梳理
本篇文章主要介紹了表達(dá)式樹 Expression Trees的基礎(chǔ)知識(shí):Lambda 表達(dá)式創(chuàng)建表達(dá)式樹;API 創(chuàng)建表達(dá)式樹;編譯表達(dá)式樹;執(zhí)行表達(dá)式樹;修改表達(dá)式樹等等,具有一定的參考價(jià)值,下面跟著小編一起來看下吧2017-01-01
解析數(shù)字簽名的substring結(jié)構(gòu)(獲取數(shù)字簽名時(shí)間)
解析數(shù)字簽名的substring結(jié)構(gòu),大家參考使用吧2013-12-12

