无法使用 htmlagilitypack 从 https URL 下载 HTML 数据

Can't download HTML data from https URL using htmlagilitypack

我有一个“小”问题 htmlagilitypack(HAP)。当我尝试从网站获取数据时出现此错误:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: 'gzip' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

我正在使用这段代码从网站获取数据:

HtmlWeb page = new HtmlWeb();
var url = "https://kat.cr/";
var data = page.Load(url);

在这段代码之后我得到了那个错误。我尝试了 google 中的所有方法,但没有任何帮助。

谁能告诉我如何解决这个问题?

谢谢

HtmlWeb不支持https下载。因此,您可以使用 WebClienta bit of modification 来自动解压缩 GZip :

class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        return request;
    }
}

然后使用 HtmlDocument.LoadHtml() 从 HTML 字符串填充您的 HtmlDocument 实例:

var url = "https://kat.cr/";
var data = new MyWebClient().DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(data);

可以在使用HtmlWeb时拦截请求,根据自己的需要修改

var page = new HtmlWeb()
{
  PreRequest = request =>
  {
    // Make any changes to the request object that will be used.
    request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
    return true;
  }
};

var url = "https://kat.cr/";
var data = page.Load(url);