LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#网页采集数据的几种方式(WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)

admin
2017年2月16日 16:25 本文热度 5908

获取网页数据有很多种方式。在这里主要讲述通过WebClient、WebBrowser和HttpWebRequest/HttpWebResponse三种方式获取网页内容。

这里获取的是包括网页的所有信息。如果单纯需要某些数据内容。可以自己构造函数甄别抠除出来!一般的做法是根据源码的格式,用正则来过滤出你需要的内容部分。

一、通过WebClient获取网页内容

这是一种很简单的获取方式,当然,其它的获取方法也很简单。在这里首先要说明的是,如果为了实际项目的效率考虑,需要考虑在函数中分配一个内存区域。大概写法如下

[csharp] view plain copy
 print?
  1. //MemoryStream是一个支持储存区为内存的流。  
  2.  byte[] buffer = new byte[1024];  
  3.  using (MemoryStream memory = new MemoryStream())  
  4.     {  
  5.     int index = 1, sum = 0;  
  6.     while (index * sum < 100 * 1024)  
  7.     {  
  8.        index = reader.Read(buffer, 0, 1024);  
  9.        if (index > 0)  
  10.        {  
  11.            memory.Write(buffer, 0, index);  
  12.             sum += index;  
  13.        }  
  14.     }  
  15.     //网页通常使用utf-8或gb2412进行编码  
  16.     Encoding.GetEncoding("gb2312").GetString(memory.ToArray());  
  17.     if (string.IsNullOrEmpty(html))  
  18.     {  
  19.         return html;  
  20.     }  
  21.     else  
  22.     {  
  23.         Regex re = new Regex(@"charset=(? charset[/s/S]*?)[ |'']");  
  24.         Match m = re.Match(html.ToLower());  
  25.         encoding = m.Groups[charset].ToString();  
  26.     }  
  27.     if (string.IsNullOrEmpty(encoding) || string.Equals(encoding.ToLower(), "gb2312"))  
  28.     {  
  29.        return html;  
  30.     }  
  31. }  
好了,现在进入正题,WebClient获取网页数据的代码如下
[csharp] view plain copy
 print?
  1. //using System.IO;  
  2. try  
  3. {  
  4.     WebClient webClient = new WebClient();  
  5.     webClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据  
  6.     Byte[] pageData = webClient.DownloadData("http://www.360doc.com/content/11/0427/03/1947337_112596569.shtml");  
  7.     //string pageHtml = Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312,则使用这句         
  8.     string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句  
  9.     using (StreamWriter sw = new StreamWriter("e:\\ouput.txt"))//将获取的内容写入文本  
  10.     {  
  11.         htm = sw.ToString();//测试StreamWriter流的输出状态,非必须  
  12.         sw.Write(pageHtml);  
  13.     }  
  14. }  
  15. catch (WebException webEx)  
  16. {  
  17.     Console.W  
  18. }  

二、通过WebBrowser控件获取网页内容

相对来说,这是一种最简单的获取方式。拖WebBrowser控件进去,然后匹配下面这段代码

[csharp] view plain copy
 print?
  1. WebBrowser web = new WebBrowser();  
  2. web.Navigate("http://www.163.com");  
  3. web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);  
  4. void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)  
  5. {  
  6.      WebBrowser web = (WebBrowser)sender;  
  7.      HtmlElementCollection ElementCollection = web.Document.GetElementsByTagName("Table");  
  8.      foreach (HtmlElement item in ElementCollection)  
  9.      {  
  10.          File.AppendAllText("Kaijiang_xj.txt", item.InnerText);  
  11.      }  
  12. }  

三、使用HttpWebRequest/HttpWebResponse获取网页内容

这是一种比较通用的获取方式。

[csharp] view plain copy
 print?
  1. public void GetHtml()  
  2.      {  
  3.          var url = "http://www.360doc.com/content/11/0427/03/1947337_112596569.shtml";  
  4.          string strBuff = "";//定义文本字符串,用来保存下载的html  
  5.          int byteRead = 0;   
  6.            
  7.          HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);  
  8.          HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();  
  9.          //若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理   
  10.          Stream reader = webResponse.GetResponseStream();  
  11.          ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)  
  12.          StreamReader respStreamReader = new StreamReader(reader,Encoding.UTF8);  
  13.   
  14.          ///分段,分批次获取网页源码  
  15.          char[] cbuffer = new char[1024];  
  16.          byteRead = respStreamReader.Read(cbuffer,0,256);  
  17.   
  18.          while (byteRead != 0)  
  19.          {  
  20.              string strResp = new string(char,0,byteRead);  
  21.              strBuff = strBuff + strResp;  
  22.              byteRead = respStreamReader.Read(cbuffer,0,256);  
  23.          }  
  24.          using (StreamWriter sw = new StreamWriter("e:\\ouput.txt"))//将获取的内容写入文本  
  25.          {  
  26.              htm = sw.ToString();//测试StreamWriter流的输出状态,非必须  
  27.              sw.Write(strBuff);  
  28.          }  
  29.      }  


该文章在 2017/2/16 16:25:49 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved