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方法调 ...
随机推荐
- 六、spark常见问题总结(转载)
问题导读 1.当前集群的可用资源不能满足应用程序的需求,怎么解决? 2.内存里堆的东西太多了,有什么好办法吗? 1.WARN TaskSchedulerImpl: Initial jo ...
- Matlab最新的官方文档中文翻译
文章翻译的是Matlab最新的官方文档R2016b,可能后续如果我还有时间会继续翻译,希望能够帮到大家,翻译的不好请大家不要吐槽. Matlab官方文档地址:http://cn.mathworks.c ...
- 第一百三十四节,JavaScript,封装库--遮罩锁屏
JavaScript,封装库--遮罩锁屏 封装库新增1个方法 /** zhe_zhao_suo_ping()方法,将一个区块元素设置成遮罩锁屏区块 * 注意:一般需要在css文件将元素设置成隐藏 ** ...
- Xtrabackup 使用stream输出并压缩备份
mysql:5.6.29xtrabackup:2.2.10mysql数据目录:/data/mysqlmysql备份目录:/data/dbbak/full #确保有足够的磁盘空间 1.安装依赖 yum ...
- shell-正则表达式
证则表达式:在计算机科学中,是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串.在很多文本编辑器或其他工具里,正则表达式通常被用来检索和/或替换那些符合某个模式的文本内容.许多程序设计 ...
- ng动态显示和隐藏
<!DOCTYPE html><html><head><meta charset="utf-8"><script src=&q ...
- C# IIS7.0+ Web.Config 配置Session过期时间
1. 2. 3. <sessionState mode="InProc" timeout="120"></sessionState>
- 字符函数库 - cctype 和 climits 中的符号常量
一. C++从C语言中继承一个与字符相关的.非常方便的函数软件包,他可以简化诸如确定字符是否为大写字母‘数字.标点符号等工作,这些函数的原型在头文件cctype(老式的为ctype.h)中定义的.例如 ...
- DB2数据库实例创建与删除 学习笔记
以root身份执行 $DB2HOME/instance/db2idrop -f 实例名,注意一定要加-f,否则不会删除实例下面sqllib文件.如果不幸忘了,执行db2icrt,会报sqllib文件存 ...
- python绝技 — 用Scapy解析TTL字段的值
#!/usr/bin/env python #--*--coding=utf-8--*-- #打印收到的数据包的源IP和TTL值 from scapy.all import * def testTTL ...