我如何使用HTML Agility Pack?
我的XHTML文档并不完全有效.这就是我想要使用它的原因.我如何在我的项目中使用它?我的项目是在C#中.
我正在重新审视我的旧代码,并且偶然发现了一种基于其网址获取网站标题的方法.这并不是你所谓的稳定方法,因为它经常无法产生结果,有时甚至会产生不正确的结果.此外,有时它无法显示标题中的某些字符,因为它们是替代编码.
有没有人对这个旧版本有改进建议?
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();
}
} …Run Code Online (Sandbox Code Playgroud)