我們如果在項目中碰到要處理HTML,如果是.NET程序員的話,強烈推薦使用NSoup,不然的話截取字符串是在是太痛苦了。NSoup是一個開源框架,是JSoup的.NET移植版本,使用方法基本一致!NSoup點擊下載
獲取網頁的html代碼
<span style="font-family: Arial, Helvetica, sans-serif;">NSoup.Nodes.Document doc = NSoup.NSoupClient.Connect("http://blog.csdn.net/dingxiaowie2013").Get();</span>
NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(HtmlString);
但是很遺憾NSoup默認的是UTF-8,處理中文會有亂碼(對於編碼是UTF-8自然會正常,但是有些是GB2312的就可能有亂碼)
1.下載網頁源代碼再處理
//下載網頁源代碼
WebClient webClient = new WebClient();
string htmlString = Encoding.GetEncoding("utf-8").GetString(webClient.DownloadData("http://www.baidu.com"));
NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(htmlString);
2.獲得網頁的流
//獲得網頁流
WebRequest webRequest = WebRequest.Create("http://blog.csdn.net/dingxiaowei2013");
NSoup.Nodes.Document doc1 = NSoup.NSoupClient.Parse(webRequest.GetResponse().GetResponseStream(), "utf-8");
效果圖
會發現跟百度的源碼是一樣的