【问题标题】:How to read html source from a HTTPS url [closed]如何从 HTTPS url 读取 html 源代码 [关闭]
【发布时间】:2013-05-30 06:08:21
【问题描述】:

我正在尝试使用以下代码读取 c# 中 https url 的 html 源代码:

 WebClient webClient = new WebClient();
 string htmlString = w.DownloadString("https://www.targetUrl.com");

这对我不起作用,因为我得到了编码的 html 字符串。我尝试使用 HtmlAgilityPack 但没有任何帮助。

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlString);

【问题讨论】:

  • this doesn't work for me as i get encoded html string 是什么意思?
  • 表示它不适用于targetUrl.com的HTTPS链接
  • WebClient.DownloadString 不需要执行任何特殊操作即可从 https 地址下载。你是什​​么意思“编码”?你怎么知道它是编码的?它看起来像什么?
  • 我们这里没有水晶球。你能指望什么?你看到了什么?你得到什么例外?

标签: c# html .net html-agility-pack


【解决方案1】:

该 URL 正在返回一个 gzip 压缩字符串。 WebClient 默认情况下不支持此功能,因此您需要转而使用底层的 HttpWebRequest 类。 feroze 在这里公然剽窃答案 - Automatically decompress gzip response via WebClient.DownloadData

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

【讨论】:

  • 是的,它也适用于example.com url,但不适用于example.com
  • @kavitaverma 然后下载带有WebClient.DownloadData的页面并自行解压。
【解决方案2】:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
WebClient webClient = new WebClient();
string htmlString = webClient.DownloadString(url);

【讨论】:

  • 您可能应该在代码中添加一些注释,以明确您的答案与已接受的答案相比有何相关性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多