如何使用C#下载具有正确编码的HTML页面?

yel*_*ood 2 c# encoding screen-scraping

我需要一个获取页面链接并返回此页面标题的方法.

我用过WebClient -

        var webClient = new WebClient();
        var htmlString = webClient.DownloadString(_link);
Run Code Online (Sandbox Code Playgroud)

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

是否有通用的方法来识别页面的编码并使用它?我需要它来支持大多数编码,如果不是全部的话.

m0s*_*0sa 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;
}
Run Code Online (Sandbox Code Playgroud)