搜索网络,发现C#通常有三种方法获取网页内容,使用WebClient、WebBrowser或者HttpWebRequest/HttpWebResponse。。。

方法一:使用WebClient (引用自:http://fbljava.blog.163.com/blog/static/265211742008712105145244/

static void Main(string[] args)

{

try {

WebClient MyWebClient = new WebClient();

MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据

Byte[] pageData = MyWebClient.DownloadData(“http://www.163.com”); //从指定网站下载数据

string pageHtml = Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312,则使用这句

//string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句

Console.WriteLine(pageHtml);//在控制台输入获取的内容

using (StreamWriter sw = new StreamWriter("c:\\test\\ouput.html"))//将获取的内容写入文本

{

sw.Write(pageHtml);

}

Console.ReadLine(); //让控制台暂停,否则一闪而过了

}

catch(WebException webEx) {

Console.WriteLine(webEx.Message.ToString());

}

}

方法二:使用WebBrowser (引用自:http://topic.csdn.net/u/20091225/14/4ea221cd-4c1e-4931-a6db-1fd4ee7398ef.html

WebBrowser web = new WebBrowser(); 
web.Navigate("http://www.xjflcp.com/ssc/"); 
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 (引用自:http://hi.baidu.com/onlyafar/blog/item/7ac4c6bf92d4810019d81f98.html

HttpWebRequest httpReq; 
HttpWebResponse httpResp;

string strBuff = ""; 
char[] cbuffer = new char[256]; 
int byteRead = 0;

string filename = @"c:\log.txt"; 
///定义写入流操作 
public void WriteStream() 

Uri httpURL = new Uri(txtURL.Text);

///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换 
      httpReq = (HttpWebRequest)WebRequest.Create(httpURL);

httpReq .UserAgent = @"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
httpReq .Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";

///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换

httpResp = (HttpWebResponse) httpReq.GetResponse(); 
///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容

///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理 
Stream respStream = httpResp.GetResponseStream();

///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以

StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8) 
StreamReader respStreamReader = new StreamReader(respStream,Encoding.UTF8);

byteRead = respStreamReader.Read(cbuffer,0,256);

while (byteRead != 0) 

string strResp = new string(cbuffer,0,byteRead); 
                  strBuff = strBuff + strResp; 
                  byteRead = respStreamReader.Read(cbuffer,0,256); 
}

respStream.Close(); 
txtHTML.Text = strBuff; 
}

C#获取网页内容的三种方式(转)的更多相关文章

  1. C#获取网页内容的三种方式

    C#通常有三种方法获取网页内容,使用WebClient.WebBrowser或者HttpWebRequest/HttpWebResponse... 方法一:使用WebClient (引用自:http: ...

  2. 获取Type的三种方式

    using System;using UnityEngine; public class Type_Test : MonoBehaviour{    private void Awake()    { ...

  3. java 获取时间戳的三种方式

      java 获取时间戳的三种方式 CreationTime--2018年7月13日16点29分 Author:Marydon 1.实现方式 方式一:推荐使用 System.currentTimeMi ...

  4. 【Struts2】Struts2获取session的三种方式

    1.Map<String,Object> map =  ActionContext.getContext().getSession(); 2.HttpSession session = S ...

  5. js获取时间戳的三种方式

      js获取时间戳的三种方式 CreateTime--2018年5月23日08:44:10 Author:Marydon // 方式一:推荐使用 var timestamp=new Date().ge ...

  6. Struts2(四.注册时检查用户名是否存在及Action获取数据的三种方式)

    一.功能 1.用户注册页面 <%@ page language="java" contentType="text/html; charset=UTF-8" ...

  7. java:struts框架2(方法的动态和静态调用,获取Servlet API三种方式(推荐IOC(控制反转)),拦截器,静态代理和动态代理(Spring AOP))

    1.方法的静态和动态调用: struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCT ...

  8. Struts2获取Session的三种方式

    1.Map<String,Object> session =  ActionContext.getContext().getSession(); session.put("cod ...

  9. 【深入Struts2】获取ServletAPI的三种方式

    一:获取servletAPI的三种方法 在传统的Web开发中,经常会用到Servlet API中的HttpServletRequest.HttpSession和ServletContext.Strut ...

随机推荐

  1. ELK之logstash收集日志写入redis及读取redis

    logstash->redis->logstash->elasticsearch 1.安装部署redis cd /usr/local/src wget http://download ...

  2. Theam,style

    Theam <!-- Base application theme. --> <!--<style name="AppTheme" parent=" ...

  3. Eclipse的调试功能(转)(让Eclipse也能有VS的即时窗口那样的即时代码调试功能)

    前言:可以很明确的说明,eclipse也有像vs那样的即时窗口来运行即时代码的功能. 调试的界面如下: 如果要像vs那样的即时调试功能,需要做一些设置,就是Expressions功能. 开通步骤:Wi ...

  4. 如何在window上把你的项目提交到github

    1.首先你需要在https://github.com/ 上注册一个账户 2.注册成功以后,你需要新建一个repository(储藏室),这个用来存放你要上传的项目 点击中间的带加号的图标就可以新建re ...

  5. Define Custom Data Filter Using Pre-Query Trigger In Oracle Forms

    Oracle Forms is having its default records filter, which we can use through Enter Query mode to spec ...

  6. linux yum 安装软件

    概括了部分常用的yum命令包括: 自动搜索最快镜像插件:yum install yum-fastestmirror安装yum图形窗口插件:yum install yumex 1 安装yum insta ...

  7. OpenCV3.1使用SIFT

    待完善... Opencv3.1.0+opencv_contrib配置及使用SIFT测试

  8. Linux学习之十二-Linux文件属性

    Linux文件属性 在Linux中,对于每个文件都有相应属性,以Linux中root用户家目录下新建文件a.txt为例,在a.txt中输入几个字符 使用命令ls -ild a.txt查看文件的权限等 ...

  9. 奇怪!post提交 地址栏参数竟然可见

    转:    http://blog.csdn.net/yuebinghaoyuan/article/details/7727802 在做项目中,form标签中method="post&quo ...

  10. 2.配置通过数据库接收SaltStack批量管理日志

    2.配置通过数据库接收SaltStack批量管理日志 2016-07-04 10:02:52来源:oschina作者:eddy_linux人点击     默认情况下发送给salt minion的命令执 ...