首页 > 学院 > 开发设计 > 正文

根据网页链接获取网页标题

2019-11-08 01:39:19
字体:
来源:转载
供稿:网友
   public String getTitle(String url)        {            //请求资源              System.Net.WebRequest wb = System.Net.WebRequest.Create(url.Trim());            //响应请求              WebResponse webRes = null;            //将返回的数据放入流中              Stream webStream = null;            try            {                webRes = wb.GetResponse();                webStream = webRes.GetResponseStream();            }            catch (Exception e)            {                return "输入的网址不存在或非法...";            }            //从流中读出数据  (这里如果乱码改变编码即可)            StreamReader sr = new StreamReader(webStream, System.Text.Encoding.UTF8);            //创建可变字符对象,用于保存网页数据               StringBuilder sb = new StringBuilder();            //读出数据存入可变字符中              String str = "";            while ((str = sr.ReadLine()) != null)            {                sb.Append(str);            }            //建立获取网页标题正则表达式              String regex = @"<title>.+</title>";            //返回网页标题              String title = Regex.Match(sb.ToString(), regex).ToString();            title = Regex.Replace(title, @"[/""]+", "");            return title;        }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表