C#获取网页内容 (WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)
获取网页数据有很多种方式。在这里主要讲述通过WebClient、WebBrowser和HttpWebRequest/HttpWebResponse三种方式获取网页内容。
这里获取的是包括网页的所有信息。如果单纯需要某些数据内容。可以自己构造函数甄别抠除出来!一般的做法是根据源码的格式,用正则来过滤出你需要的内容部分。
一、通过WebClient获取网页内容
这是一种很简单的获取方式,当然,其它的获取方法也很简单。在这里首先要说明的是,如果为了实际项目的效率考虑,需要考虑在函数中分配一个内存区域。大概写法如下
- //MemoryStream是一个支持储存区为内存的流。
- byte[] buffer = new byte[1024];
- using (MemoryStream memory = new MemoryStream())
- {
- int index = 1, sum = 0;
- while (index * sum < 100 * 1024)
- {
- index = reader.Read(buffer, 0, 1024);
- if (index > 0)
- {
- memory.Write(buffer, 0, index);
- sum += index;
- }
- }
- //网页通常使用utf-8或gb2412进行编码
- Encoding.GetEncoding("gb2312").GetString(memory.ToArray());
- if (string.IsNullOrEmpty(html))
- {
- return html;
- }
- else
- {
- Regex re = new Regex(@"charset=(? charset[/s/S]*?)[ |']");
- Match m = re.Match(html.ToLower());
- encoding = m.Groups[charset].ToString();
- }
- if (string.IsNullOrEmpty(encoding) || string.Equals(encoding.ToLower(), "gb2312"))
- {
- return html;
- }
- }
//MemoryStream是一个支持储存区为内存的流。
byte[] buffer = new byte[1024];
using (MemoryStream memory = new MemoryStream())
{
int index = 1, sum = 0;
while (index * sum < 100 * 1024)
{
index = reader.Read(buffer, 0, 1024);
if (index > 0)
{
memory.Write(buffer, 0, index);
sum += index;
}
}
//网页通常使用utf-8或gb2412进行编码
Encoding.GetEncoding("gb2312").GetString(memory.ToArray());
if (string.IsNullOrEmpty(html))
{
return html;
}
else
{
Regex re = new Regex(@"charset=(? charset[/s/S]*?)[ |']");
Match m = re.Match(html.ToLower());
encoding = m.Groups[charset].ToString();
}
if (string.IsNullOrEmpty(encoding) || string.Equals(encoding.ToLower(), "gb2312"))
{
return html;
}
}
好了,现在进入正题,WebClient获取网页数据的代码如下
- //using System.IO;
- try
- {
- WebClient webClient = new WebClient();
- webClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
- Byte[] pageData = webClient.DownloadData("http://www.360doc.com/content/11/0427/03/1947337_112596569.shtml");
- //string pageHtml = Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句
- string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句
- using (StreamWriter sw = new StreamWriter("e:\\ouput.txt"))//将获取的内容写入文本
- {
- htm = sw.ToString();//测试StreamWriter流的输出状态,非必须
- sw.Write(pageHtml);
- }
- }
- catch (WebException webEx)
- {
- Console.W
- }
//using System.IO;
try
{
WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
Byte[] pageData = webClient.DownloadData("http://www.360doc.com/content/11/0427/03/1947337_112596569.shtml");
//string pageHtml = Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句
string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句
using (StreamWriter sw = new StreamWriter("e:\\ouput.txt"))//将获取的内容写入文本
{
htm = sw.ToString();//测试StreamWriter流的输出状态,非必须
sw.Write(pageHtml);
}
}
catch (WebException webEx)
{
Console.W
}
二、通过WebBrowser控件获取网页内容
相对来说,这是一种最简单的获取方式。拖WebBrowser控件进去,然后匹配下面这段代码
- WebBrowser web = new WebBrowser();
- web.Navigate("http://www.163.com");
- web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
- void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
- {
- WebBrowser web = (WebBrowser)sender;
- HtmlElementCollection ElementCollection = web.Document.GetElementsByTagName("Table");
- foreach (HtmlElement item in ElementCollection)
- {
- File.AppendAllText("Kaijiang_xj.txt", item.InnerText);
- }
- }
WebBrowser web = new WebBrowser();
web.Navigate("http://www.163.com");
web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser web = (WebBrowser)sender;
HtmlElementCollection ElementCollection = web.Document.GetElementsByTagName("Table");
foreach (HtmlElement item in ElementCollection)
{
File.AppendAllText("Kaijiang_xj.txt", item.InnerText);
}
}
三、使用HttpWebRequest/HttpWebResponse获取网页内容
这是一种比较通用的获取方式。
- public void GetHtml()
- {
- var url = "http://www.360doc.com/content/11/0427/03/1947337_112596569.shtml";
- string strBuff = "";//定义文本字符串,用来保存下载的html
- int byteRead = 0;
- HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
- HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
- //若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理
- Stream reader = webResponse.GetResponseStream();
- ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)
- StreamReader respStreamReader = new StreamReader(reader,Encoding.UTF8);
- ///分段,分批次获取网页源码
- char[] cbuffer = new char[1024];
- byteRead = respStreamReader.Read(cbuffer,0,256);
- while (byteRead != 0)
- {
- string strResp = new string(char,0,byteRead);
- strBuff = strBuff + strResp;
- byteRead = respStreamReader.Read(cbuffer,0,256);
- }
- using (StreamWriter sw = new StreamWriter("e:\\ouput.txt"))//将获取的内容写入文本
- {
- htm = sw.ToString();//测试StreamWriter流的输出状态,非必须
- sw.Write(strBuff);
- }
- }
C#获取网页内容 (WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)的更多相关文章
- C#网页采集数据的几种方式(WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)
一.通过WebClient获取网页内容 这是一种很简单的获取方式,当然,其它的获取方法也很简单.在这里首先要说明的是,如果为了实际项目的效率考虑,需要考虑在函数中分配一个内存区域.大概写法如下 //M ...
- C#获取网页内容的三种方式
C#通常有三种方法获取网页内容,使用WebClient.WebBrowser或者HttpWebRequest/HttpWebResponse... 方法一:使用WebClient (引用自:http: ...
- C#获取网页内容的三种方式(转)
搜索网络,发现C#通常有三种方法获取网页内容,使用WebClient.WebBrowser或者HttpWebRequest/HttpWebResponse... 方法一:使用WebClient (引用 ...
- 【C#】获取网页内容及HTML解析器HtmlAgilityPack的使用
最近经常需要下载一些东西,而这个下载地址又会经过层层跳转,每个页面上都有很多广告,烦不胜烦,所以做了一个一键获得最终下载地址的小工具.使用C#,来获取网页内容,然后通过HtmlAgilityPack获 ...
- HttpWebRequest,HttpWebResponse的用法和用途
1.用途:HettpWebRequest,HettpWebResponse用途和webServers的作用差不多,都是得到一个页面传过来的值.HttpWebRequest 2.用法:--------- ...
- 定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容。提示(可以了解python的urllib模块)
定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容.提示(可以了解python的urllib模块) import urllib.request def get_ ...
- 使用Jsoup获取网页内容超时设置
使用Jsoup获取网页内容超时设置 最近使用Jsoup来抓取网页,并对网页进行解析,发现很好用.在抓取过程中遇到一个问题,有些页面总是报Timeout异常,开始想是不是被抓取网站对IP进行了限制,后来 ...
- 基于apache —HttpClient的小爬虫获取网页内容
今天(17-03-31)忙了一下午研究webmagic,发现自己还太年轻,对于这样难度的框架(类库) 还是难以接受,还是从基础开始吧,因为相对基础的东西教程相多一些,于是乎我找了apache其下的 H ...
- 使用selenium和phantomJS浏览器获取网页内容的小演示
# 使用selenium和phantomJS浏览器获取网页内容的小演示 # 导入包 from selenium import webdriver # 使用selenium库里的webdriver方法调 ...
随机推荐
- 近期unity ios接入的事情
1, 在接入苹果内支付的时候,遇到一个很严重的问题,使用的公司的moni2来测试的,但是在测试的过程中发现每次调用oc的内支付代码后,总会先回调一个支付成功,然后弹出输入密码框,当点击取消后,再一次 ...
- 【C#】【SHARE】The registering of global hotkeys
I remember that when I was still using VB6 sereval years ago, if global hotkeys are required, a mass ...
- OO的五大原则:SRP、OCP、LSP、DIP、ISP
OO的五大原则是指SRP.OCP.LSP.DIP.ISP. SRP -- (Single Responsibility Principle 单一职责原则) OCP--开闭原则(Closed for M ...
- make -j 多核并行编译 导致笔记本过热 自动关机保护
中午在装着CentOS的笔记本上把 Oneinstack 跑起来然后去上班了,本来等着下班回来用的,回来之后发现是关机状态,环境也没有装好. 查看日志,找不到相关信息,甚至还以为是被入侵了.又试了几遍 ...
- Android 6.0 M userdebug版本执行adb remount失败
[FAQ18076]Android 6.0 M版本默认会打开system verified boot,即在userdebug和user版本会把system映射到dm-0设备,然后再挂载.挂载前会检查s ...
- 使用navicat连接远程linux的mysql中文显示乱码的问题
在navicat对应的连接上 右键->连接属性->高级 去掉使用mysql字符集 然后上面的编码选择 (65001)utf-8 接着打开连接 找到对应的数据库 右键 数据库属性 把编码 ...
- arm指令集
http://blog.chinaunix.net/uid-20769502-id-112445.html
- 前端必知的ajax
简介 异步交互 此篇只介绍部分方法,想了解更多就猛戳这里 1. load( url, [data], [callback] ) :载入远程 HTML 文件代码并插入至 DOM 中. url (Stri ...
- 敏捷开发(八)- Scrum Sprint计划会议1
本文主要是为了检测你对SCRUM Sprint 计划会议的了解和使用程度, 通过本文你可以检测一下 1.你们的SCRUM Sprint 计划会议的过程和步骤 2.会议的输出结果 S ...
- Angular-ui-router + oclazyload + requirejs实现资源随route懒加载
刚开始用angularjs做项目的时候,我用的是ng-router,觉得加载并不好.所以就用了ui-router,考虑到在app上网页加载速度太慢,所以我就想到了用懒加载,看下是否能提升性能,提高加载 ...