【问题标题】:Webclient Download String returns unexpected resultsWebclient 下载字符串返回意外结果
【发布时间】:2015-03-31 01:01:13
【问题描述】:

我有这个功能来下载一个网站的 html 代码,但是当我输入这个特定的网站时,它返回一个点(。)而不是 html 代码,谁能告诉我哪里出了问题或者为什么它没有重新调整代码?

网址:“http://bato.to/comic/_/nisekoi-r951

代码:

        public string DownloadString(string add)
        {
            string html = "";            
            using (WebClient client = new WebClient())
            {
                client.Proxy = null;
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");                
                while (html=="")
                {
                    try
                    {
                        html = client.DownloadString(add);
                        //MessageBox.Show(html);       
                    }
                    catch
                    {
                        html = "";
                    }
                }
                client.Dispose();
            }
            return html;
        }

感谢您的帮助。

【问题讨论】:

  • 它实际上返回 null,还是抛出异常并因此设置为空字符串?
  • 首先,httl:// 变成http://
  • 它返回 null 因为在其他网站上它可以工作。
  • 不要说它返回 null 因为在其他网站上它可以工作,说它返回 null 因为它没有在 catch 子句中遇到断点。是吗?
  • 那不是一个有效的逻辑链。您是否设置了断点并验证了 DownloadString 执行后的 html == null,并且它没有命中 catch 块?

标签: c# webclient


【解决方案1】:

您需要在该网站上使用“https”:

 public static string DownloadString(string add)
        {
            using (var client = new WebClient())
            {
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                return client.DownloadString(add);
            }
        }

调用代码:

Console.WriteLine(DownloadString("https://bato.to/comic/_/nisekoi-r951"));

示例响应:

               <div class='ipbfs_login_col'>
                    <input type='checkbox' id='inline_invisible' name='anonymous
' value='1' class='input_check left' />
                    <div style='padding-left: 20px;'>
                        <label for='inline_invisible'>
                            <strong>Sign in anonymously</strong>
                            <span class='desc lighter' style='display: block; pa
dding-top: 5px;'>Don't add me to the active users list</span>
                        </label>
                    </div>
                </div>

【讨论】:

    猜你喜欢
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多