c# - 如何从c#获取网站标题

标签 c# webrequest

我正在重温我的一些旧代码,偶然发现了一种根据网址获取网站标题的方法。这并不是真正意义上的稳定方法,因为它经常无法产生结果,有时甚至会产生不正确的结果。此外,有时它无法显示标题中的某些字符,因为它们是另一种编码。

有没有人对这个旧版本有改进的建议?

public static string SuggestTitle(string url, int timeout)
{
    WebResponse response = null;
    string line = string.Empty;

    try
    {
        WebRequest request = WebRequest.Create(url);
        request.Timeout = timeout;

        response = request.GetResponse();
        Stream streamReceive = response.GetResponseStream();
        Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader streamRead = new System.IO.StreamReader(streamReceive, encoding);

        while(streamRead.EndOfStream != true)
        {
            line = streamRead.ReadLine();
            if (line.Contains("<title>"))
            {
                line = line.Split(new char[] { '<', '>' })[2];
                break;
            }
        }
    }
    catch (Exception) { }
    finally
    {
        if (response != null)
        {
            response.Close();
        }
    }

    return line;
}

最后一点 - 我希望代码也能运行得更快,因为它会阻塞直到页面被获取,所以如果我只能获取站点标题而不是整个页面,那就太好了。

最佳答案

获取内容的更简单方法:

WebClient x = new WebClient();
string source = x.DownloadString("http://www.singingeels.com/");

获取标题的更简单、更可靠的方法:

string title = Regex.Match(source, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>",
    RegexOptions.IgnoreCase).Groups["Title"].Value;

关于c# - 如何从c#获取网站标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/329307/

相关文章:

google-chrome - 在 Chrome 扩展程序中读取和修改 HTTP GET 请求

Python BeautifulSoup 检查输出

powershell - 如何在Powershell中正确使用发布请求

c# - 确定具有 FlagsAttribute 的枚举是否具有唯一的位值

c# - 我可以检测对象是否调用了 GC.SuppressFinalize 吗?

c# - 在非静态类中调用静态方法时是否实例化了一个类?

c# httpwebrequest getResponse() 卡住并挂起我的程序

C# 处理空格

c# - 分组项目页 : View jumps back to start when navigating back from detailpage

google-chrome - 使用 Google Chrome webRequest API 进行简单转发