【问题标题】:How to get title of web page with web client?如何使用 Web 客户端获取网页标题?
【发布时间】:2020-04-22 10:40:53
【问题描述】:

我的网络客户端连接有问题。在大多数站点上,获取页面标题没有问题,但是当我测试它时发现一个站点引发错误“底层连接已关闭:接收时发生意外错误。”具体网站是:“https://www.modbee.com/opinion/letters-to-the-editor/article111712867.html”。

private string GetTitle(string link)
    {
        try
        {
            string html = webClient.DownloadString(link);
            Regex reg = new Regex("<title>(.*)</title>");
            MatchCollection m = reg.Matches(html);
            if (m.Count > 0)
            {
                return m[0].Value.Replace("<title>", "").Replace("</title>", "");
            }
            else
                return "";
        }
        catch (Exception e)
        {
            return labelError.Text = "You should insert correct URL\n";
        }

    }

【问题讨论】:

  • 你可以检查服务器结果代码,或者包裹在 try/catch 中,如果失败则返回 null 或 String.Empty?
  • 从那个主题尝试了所有,但正如我所说,我成功地从大多数网站获得标题,但不小心尝试了这个页面并在网络客户端尝试从我通过的 url 下载字符串的线上引发异常给它

标签: c# .net webclient


【解决方案1】:

如果你想下载html并测试正则表达式,你可以使用下面的代码sn-p。

    /*usage:*/
//HttpGet(new Uri("https://www.modbee.com/opinion/letters-to-the-editor/article111712867.html"));

public static string HttpGet(Uri uri) {
 HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
 request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

 using(HttpWebResponse response = (HttpWebResponse) request.GetResponse())
 using(Stream stream = response.GetResponseStream())
 using(StreamReader reader = new StreamReader(stream)) {
  var str = reader.ReadToEnd();
  Regex reg = new Regex("<title>(.*)</title>");
  MatchCollection m = reg.Matches(str);
  if (m.Count > 0) {
   return m[0].Value.Replace("<title>", "").Replace("</title>", "");
  } else
   return "";
 }
}

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 1970-01-01
    • 2012-06-25
    • 2019-03-29
    • 2019-01-02
    • 2021-05-23
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多