C# HTMLHelper类对Html源码处理教程与源码下载

来源:互联网 发布:linux 重启 编辑:程序博客网 时间:2024/05/22 17:19
导读部分
-------------------------------------------------------------------------------------------------------------
C#基类|C#自定义类|C#帮助类--系列导航文章
http://www.sufeinet.com/thread-655-1-1.html

源码下载,请到基库中直接查找http://www.sufeinet.com/thread-655-1-1.html
主要功能有
[C#] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
1.获取HTML源代码
2.获取Html源代码的字符流
3.清理所有的Html标记,标签
4.匹配页面的链接,获取Html中所有的A链接
5.匹配页面的图片地址 ,获取Html中所有的图片地址
6.抓取远程页面内容
7.压缩HTML输出
8.过滤指定HTML标签
9.加载文件块
10.加载CSS样式文件
11.加载JavaScript脚本文件

如下图片

[size=0.83em]QQ截图20140121085054.jpg (101.69 KB, 下载次数: 0)
下载附件
[color=rgb(153, 153, 153) !important]昨天 08:50 上传




预览源码
代码如下
[C#] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/// <summary>
/// 类说明:HTMLHelper
/// 编 码 人:苏飞
/// 联系方式:361983679 
/// 更新网站:[url=http://www.sufeinet.com/thread-655-1-1.html]http://www.sufeinet.com/thread-655-1-1.html[/url]
/// </summary>
usingSystem;
usingSystem.Text;
usingSystem.Net;
usingSystem.IO;
usingSystem.Threading;
usingSystem.Text.RegularExpressions;
 
namespaceDotNet.Utilities
{
    publicclassHTMLHelper
    {
        #region 私有字段
        privatestaticCookieContainer cc = newCookieContainer();
        privatestaticstring contentType = "application/x-www-form-urlencoded";
        privatestaticstring accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
        privatestaticstring userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
        privatestaticEncoding encoding = Encoding.GetEncoding("utf-8");
        privatestaticint delay = 1000;
        privatestaticint maxTry = 300;
        privatestaticint currentTry = 0;
        #endregion
 
        #region 公有属性
        /// <summary>
        /// Cookie
        /// </summary>
        publicstaticCookieContainer CookieContainer
        {
            get
            {
                returncc;
            }
        }
 
        /// <summary>
        /// 语言
        /// </summary>
        publicstaticEncoding Encoding
        {
            get
            {
                returnencoding;
            }
            set
            {
                encoding = value;
            }
        }
 
        publicstaticint NetworkDelay
        {
            get
            {
                Random r = newRandom();
                return(r.Next(delay, delay * 2));
            }
            set
            {
                delay = value;
            }
        }
 
        publicstaticint MaxTry
        {
            get
            {
                returnmaxTry;
            }
            set
            {
                maxTry = value;
            }
        }
        #endregion
 
        #region 获取HTML
        /// <summary>
        /// 获取HTML
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="postData">post 提交的字符串</param>
        /// <param name="isPost">是否是post</param>
        /// <param name="cookieContainer">CookieContainer</param>
        publicstaticstring GetHtml(stringurl,stringpostData,boolisPost, CookieContainer cookieContainer)
        {
            if(string.IsNullOrEmpty(postData))returnGetHtml(url, cookieContainer);
            Thread.Sleep(NetworkDelay);
            currentTry++;
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                byte[] byteRequest = Encoding.Default.GetBytes(postData);
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = contentType;
                httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
                httpWebRequest.Referer = url;
                httpWebRequest.Accept = accept;
                httpWebRequest.UserAgent = userAgent;
                httpWebRequest.Method = isPost ? "POST":"GET";
                httpWebRequest.ContentLength = byteRequest.Length;
                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(byteRequest, 0, byteRequest.Length);
                stream.Close();
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = newStreamReader(responseStream, encoding);
                stringhtml = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                currentTry = 0;
                httpWebRequest.Abort();
                httpWebResponse.Close();
                returnhtml;
            }
            catch(Exception e)
            {
                if(currentTry <= maxTry) GetHtml(url, postData, isPost, cookieContainer);
                currentTry--;
                if(httpWebRequest != null) httpWebRequest.Abort();
                if(httpWebResponse != null) httpWebResponse.Close();
                returnstring.Empty;
            }
        }
 
        /// <summary>
        /// 获取HTML
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="cookieContainer">CookieContainer</param>
        publicstaticstring GetHtml(stringurl, CookieContainer cookieContainer)
        {
            Thread.Sleep(NetworkDelay);
            currentTry++;
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = contentType;
                httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
                httpWebRequest.Referer = url;
                httpWebRequest.Accept = accept;
                httpWebRequest.UserAgent = userAgent;
                httpWebRequest.Method = "GET";
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = newStreamReader(responseStream, encoding);
                stringhtml = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                currentTry--;
                httpWebRequest.Abort();
                httpWebResponse.Close();
                returnhtml;
            }
            catch(Exception e)
            {
                if(currentTry <= maxTry) GetHtml(url, cookieContainer);
                currentTry--;
                if(httpWebRequest != null) httpWebRequest.Abort();
                if(httpWebResponse != null) httpWebResponse.Close();
                returnstring.Empty;
            }
        }
        #endregion
 
        #region 获取字符流
        /// <summary>
        /// 获取字符流
        /// </summary>
        //---------------------------------------------------------------------------------------------------------------
        // 示例:
        // System.Net.CookieContainer cookie = new System.Net.CookieContainer();
        // Stream s = HttpHelper.GetStream("http://ptlogin2.qq.com/getimage?aid=15000102&0.43878429697395826", cookie);
        // picVerify.Image = Image.FromStream(s);
        //---------------------------------------------------------------------------------------------------------------
        /// <param name="url">地址</param>
        /// <param name="cookieContainer">cookieContainer</param>
        publicstaticStream GetStream(stringurl, CookieContainer cookieContainer)
        {
            currentTry++;
 
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
 
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = contentType;
                httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
                httpWebRequest.Referer = url;
                httpWebRequest.Accept = accept;
                httpWebRequest.UserAgent = userAgent;
                httpWebRequest.Method = "GET";
 
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                currentTry--;
                returnresponseStream;
            }
            catch(Exception e)
            {
                if(currentTry <= maxTry)
                {
                    GetHtml(url, cookieContainer);
                }
 
                currentTry--;
 
                if(httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }if(httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }
                returnnull;
            }
        }
        #endregion
 
        #region 清除HTML标记
        ///<summary>  
        ///清除HTML标记  
        ///</summary>  
        ///<param name="NoHTML">包括HTML的源码</param>  
        ///<returns>已经去除后的文字</returns>  
        publicstaticstring NoHTML(stringHtmlstring)
        {
            //删除脚本  
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>","", RegexOptions.IgnoreCase);
 
            //删除HTML  
            Regex regex = newRegex("<.+?>", RegexOptions.IgnoreCase);
            Htmlstring = regex.Replace(Htmlstring, "");
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>","", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+","", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->","", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*","", RegexOptions.IgnoreCase);
 
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);","\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);","&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);","<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);",">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);","   ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);","\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);","\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);","\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);","\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);","", RegexOptions.IgnoreCase);
 
            Htmlstring.Replace("<","");
            Htmlstring.Replace(">","");
            Htmlstring.Replace("\r\n","");
 
            returnHtmlstring;
        }
        #endregion
 
        #region 匹配页面的链接
        /// <summary>
        /// 获取页面的链接正则
        /// </summary>
        publicstringGetHref(stringHtmlCode)
        {
            stringMatchVale = "";
            stringReg = @"(h|H)(r|R)(e|E)(f|F) *= *('|"")?((\w|\\|\/|\.|:|-|_)+)[\S]*";
            foreach(Match m inRegex.Matches(HtmlCode, Reg))
            {
                MatchVale += (m.Value).ToLower().Replace("href=","").Trim() + "|";
            }
            returnMatchVale;
        }
        #endregion
 
        #region 匹配页面的图片地址
        /// <summary>
        /// 匹配页面的图片地址
        /// </summary>
        /// <param name="imgHttp">要补充的http://路径信息</param>
        publicstringGetImgSrc(stringHtmlCode,stringimgHttp)
        {
            stringMatchVale = "";
            stringReg = @"<img.+?>";
            foreach(Match m inRegex.Matches(HtmlCode.ToLower(), Reg))
            {
                MatchVale += GetImg((m.Value).ToLower().Trim(), imgHttp) + "|";
            }
 
            returnMatchVale;
        }
 
        /// <summary>
        /// 匹配<img src="" />中的图片路径实际链接
        /// </summary>
        /// <param name="ImgString"><img src="" />字符串</param>
        publicstringGetImg(stringImgString,stringimgHttp)
        {
            stringMatchVale = "";
            stringReg = @"src=.+\.(bmp|jpg|gif|png|)";
            foreach(Match m inRegex.Matches(ImgString.ToLower(), Reg))
            {
                MatchVale += (m.Value).ToLower().Trim().Replace("src=","");
            }
            if(MatchVale.IndexOf(".net") != -1 || MatchVale.IndexOf(".com") != -1 || MatchVale.IndexOf(".org") != -1 || MatchVale.IndexOf(".cn") != -1 || MatchVale.IndexOf(".cc") != -1 || MatchVale.IndexOf(".info") != -1 || MatchVale.IndexOf(".biz") != -1 || MatchVale.IndexOf(".tv") != -1)
                return(MatchVale);
            else
                return(imgHttp + MatchVale);
        }
        #endregion
 
        #region 抓取远程页面内容
        /// <summary>
        /// 以GET方式抓取远程页面内容
        /// </summary>
        publicstaticstring Get_Http(stringtUrl)
        {
            stringstrResult;
            try
            {
                HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(tUrl);
                hwr.Timeout = 19600;
                HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
                Stream myStream = hwrs.GetResponseStream();
                StreamReader sr = newStreamReader(myStream, Encoding.Default);
                StringBuilder sb = newStringBuilder();
                while(-1 != sr.Peek())
                {
                    sb.Append(sr.ReadLine() + "\r\n");
                }
                strResult = sb.ToString();
                hwrs.Close();
            }
            catch(Exception ee)
            {
                strResult = ee.Message;
            }
            returnstrResult;
        }
 
        /// <summary>
        /// 以POST方式抓取远程页面内容
        /// </summary>
        /// <param name="postData">参数列表</param>
        publicstaticstring Post_Http(stringurl,stringpostData,stringencodeType)
        {
            stringstrResult = null;
            try
            {
                Encoding encoding = Encoding.GetEncoding(encodeType);
                byte[] POST = encoding.GetBytes(postData);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = POST.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(POST, 0, POST.Length); //设置POST
                newStream.Close();
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = newStreamReader(myResponse.GetResponseStream(), Encoding.Default);
                strResult = reader.ReadToEnd();
            }
            catch(Exception ex)
            {
                strResult = ex.Message;
            }
            returnstrResult;
        }
        #endregion
 
        #region 压缩HTML输出
        /// <summary>
        /// 压缩HTML输出
        /// </summary>
        publicstaticstring ZipHtml(stringHtml)
        {
            Html = Regex.Replace(Html, @">\s+?<","><");//去除HTML中的空白字符
            Html = Regex.Replace(Html, @"\r\n\s*","");
            Html = Regex.Replace(Html, @"<body([\s|\S]*?)>([\s|\S]*?)</body>",@"<body$1>$2</body>", RegexOptions.IgnoreCase);
            returnHtml;
        }
        #endregion
 
        #region 过滤指定HTML标签
        /// <summary>
        /// 过滤指定HTML标签
        /// </summary>
        /// <param name="s_TextStr">要过滤的字符</param>
        /// <param name="html_Str">a img p div</param>
        publicstaticstring DelHtml(strings_TextStr,stringhtml_Str)
        {
            stringrStr = "";
            if(!string.IsNullOrEmpty(s_TextStr))
            {
                rStr = Regex.Replace(s_TextStr, "<"+ html_Str + "[^>]*>","", RegexOptions.IgnoreCase);
                rStr = Regex.Replace(rStr, "</"+ html_Str + ">","", RegexOptions.IgnoreCase);
            }
            returnrStr;
        }
        #endregion
 
        #region 加载文件块
        /// <summary>
        /// 加载文件块
        /// </summary>
        publicstaticstring File(stringPath, System.Web.UI.Page p)
        {
            return@p.ResolveUrl(Path);
        }
        #endregion
 
        #region 加载CSS样式文件
        /// <summary>
        /// 加载CSS样式文件
        /// </summary>
        publicstaticstring CSS(stringcssPath, System.Web.UI.Page p)
        {
            return@"<link href=""" + p.ResolveUrl(cssPath) + @""" rel=""stylesheet"" type=""text/css"" />" + "\r\n";
        }
        #endregion
 
        #region 加载JavaScript脚本文件
        /// <summary>
        /// 加载javascript脚本文件
        /// </summary>
        publicstaticstring JS(stringjsPath, System.Web.UI.Page p)
        {
            return@"<script type=""text/javascript"" src=""" + p.ResolveUrl(jsPath) + @"""></script>"+"\r\n";
        }
        #endregion
    }
}

例子
比如我们要获取一个网页的源代码
[C#] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
HttpHelper http = newHttpHelper();
 
         HttpItem item = newHttpItem()
         {
             URL = "http://www.sufeinet.com",//URL     必需项   
         };
         HttpResult result = http.GetHtml(item);
 
         //这里就是获取到的压缩后的Html了
         stringhtml = HTMLHelper.ZipHtml(result.Html);

其他的方法调用和这个都一样,大家只要传不同的参数就是了。
Ok就到这里有问题跟帖吧
0 0