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);
///通過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;
}