2011-02-24 68 views
2

我需要一个获取到页面链接的方法,并返回此页面的标题。如何使用C#以正确的编码下载HTML页面?

我使用Web客户端 -

 var webClient = new WebClient(); 
     var htmlString = webClient.DownloadString(_link); 

它运作良好,但它失败外语的编码。我得到问号和奇怪的字符,而不是我需要的文字。

是否有一种通用的方法来识别页面的编码并使用它?如果不是全部,我需要它来支持大部分编码。

+0

请问网页和/或服务器指定为哪种编码它被编码? – 2011-02-24 09:57:20

+0

该网页可以是互联网上的任何网页,这就是问题:) – yellowblood 2011-02-24 10:28:22

回答

10

使用HtmlAgilityPack你可以做这样的事情

using (WebClient client = new WebClient()) 
using (var read = client.OpenRead("http://your.com")) 
{ 
    HtmlDocument doc = new HtmlDocument(); 
    doc.Load(read, true); // true = get encoding from byte order masks 
    // process doc, extract title 
    var title = doc.DocumentNode.SelectSingleNode("//title").InnerText; 
} 
+0

似乎工作,谢谢! – yellowblood 2011-02-24 11:19:16

0
using System; 
using System.IO; 
using System.Net; 
using System.Text; 

... 

    public static void GetFile 
      (
      string strURL, 
      string strFilePath 
      ) 
     { 

      WebRequest myWebRequest = WebRequest.Create(strURL); 

      WebResponse myWebResponse = myWebRequest.GetResponse(); 

      Stream ReceiveStream = myWebResponse.GetResponseStream(); 

      Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); 

      StreamReader readStream = new StreamReader(ReceiveStream, encode); 

      string strResponse=readStream.ReadToEnd(); 

      StreamWriter oSw=new StreamWriter(strFilePath); 

      oSw.WriteLine(strResponse); 

      oSw.Close(); 

      readStream.Close(); 

      myWebResponse.Close(); 

     } 
+1

这显然只适用于,如果页面确实是UTF-8!此外,它不解码HTML字符,如ü – 2011-02-24 10:00:23

相关问题