搜索网络,发现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. (2)WCF客户端调用

    一.visual studion引用生成代理 引入服务端发布元数据的地址(并不是服务的地址) 用服务端是控制台程序 例子1 服务端的配置 <system.serviceModel> < ...

  2. Write a function that generates one of 3 numbers according to given probabilities

    You are given a function rand(a, b) which generates equiprobable random numbers between [a, b] inclu ...

  3. PHP message: PHP Fatal error: require(): Failed opening required

    PHP message: PHP Warning: require(/data/wwwroot/blog.sgfoot.com/bootstrap/autoload.php): failed to o ...

  4. ArcGIS 10.2 二次开发,兼容Visual Studio 2012二次开发,完美安装教程

    GIS 经常安装是常有的事,每次重装系统都要浪费大半天去安装这个.所以凑这一次安装,把这个软件重新安装的步骤整理了一下,希望对大家有所帮助.这次整理的内容的关键优点是,对常见的出错内容进行了归纳整理. ...

  5. 快速建立ssh互信(转)

    转自:魏巍的Linux酒吧 - 51CTO技术博客(http://weiweilinux.blog.51cto.com/3349074/1048212) 快速建立ssh互信 因为工作中经常需要配置服务 ...

  6. XCode设置竖屏

    选中你的项目,在General这个标签内,Deoployment info的这个分组,有一个Device Orientation 标签,内有一个Portrait的选项,选中是竖屏,取消选中是横屏

  7. Scut游戏服务器引擎6.0.5.1发布

    1. 修正缓存删除时不会更新到Redis的问题 2. 修正Model组合3个以上子类时Change事件未绑定的问题 3. 修正中间层MySql与MsSql数据库Sql语句分页问题

  8. PHP设置头部编码为UTF-8语句

    header("Content-type: text/html; charset=utf-8");

  9. mac安装apache的mod_wsgi模块

    第一次用pip安装 ,最终不能使用,原因是系统自带的apache,python和新安装的冲突, 所以需要安装时需要指定apache,python路径 所以用make makeinstall方式 参考链 ...

  10. linux中文件描述符

    :: # cat ping.txt PING baidu.com (() bytes of data. bytes from ttl= time=32.1 ms bytes from ttl= tim ...