ASP.NET抓取网页内容的实现方法
2015-09-03 09:19
666 查看
这篇文章主要介绍了ASP.NET抓取网页内容的实现方法,涉及使用HttpWebRequest及WebResponse抓取网页内容的技巧,需要的朋友可以参考下
原文:/article/1273103.html
一、ASP.NET 使用HttpWebRequest抓取网页内容 /// <summary>方法一:比较推荐 /// 用HttpWebRequest取得网页源码 /// 对于带BOM的网页很有效,不管是什么编码都能正确识别 /// </summary> /// <param name="url">网页地址" </param> /// <returns>返回网页源文件</returns> public static string GetHtmlSource2(string url) { //处理内容 string html = ""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Accept = "*/*"; //接受任意文件 request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"; // request.AllowAutoRedirect = true;//是否允许302 //request.CookieContainer = new CookieContainer();//cookie容器, request.Referer = url; //当前页面的引用 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.Default); //这里如果出现乱码可以使用 Encoding.GetEncoding("utf-8")处理
html = reader.ReadToEnd(); stream.Close(); return html; }
二、ASP.NET 使用 WebResponse 抓取网页内容 public static string GetHttpData2(string Url) { string sException = null; string sRslt = null; WebResponse oWebRps = null; WebRequest oWebRqst = WebRequest.Create(Url); oWebRqst.Timeout = 50000; try { oWebRps = oWebRqst.GetResponse(); } catch (WebException e) { sException = e.Message.ToString(); } catch (Exception e) { sException = e.ToString(); } finally { if (oWebRps != null) { StreamReader oStreamRd = new StreamReader(oWebRps.GetResponseStream(), Encoding.GetEncoding("utf-8")); sRslt = oStreamRd.ReadToEnd(); oStreamRd.Close(); oWebRps.Close(); } } return sRslt; }
原文:/article/1273103.html
相关文章推荐
- ASP.NET5 中静态文件的各种使用方式
- ASP.NET Auto Deployment with MSBuild
- Heroku 与 ASP.NET 5
- AspectJ风格的Aop切点表达式
- spring mvc 与 jasper Report集成
- ASP.NET MVC cs类中根据Controller和Action生成URL
- 树莓派Raspberry Pi启动设置
- ASP.NET MVC模型绑定
- Aspose.Words for .NET基本介绍以及功能介绍
- Aspose.Words for .NET基本介绍以及功能介绍
- [.Net MVC] 用户角色权限管理_使用CLK.AspNet.Identity
- ASP.Net MVC开发基础学习笔记(1):走向MVC模式
- ASPxGridView的数据绑定显示
- ASP.NET - 生成验证码
- ASP.NET - 一般处理程序获取session值
- 转 ---- Asp.net mvc项目分页功能
- 关于asp.net MVC4 无法检索“mvc4.Models.Movie”的元数据
- asp.net正则表达式学习例子
- asp短信接口开发经验及具体开发实现
- ABP(现代ASP.NET样板开发框架)系列之23、ABP展现层——异常处理