.NET中获取HTML页面并提取其中的超链接
2007-03-09 23:41
381 查看
下列的函数分别用于获取HTML页面和提取页面中的超链接。
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
string[] GetLink(string strHtml)
{
Regex reg = new Regex("href[//s//r]*=[//s//r]*[/"/']{0,1}([^/"/'//s//r>]*)[/"/'//s//r]{0,1}", RegexOptions.IgnoreCase);
MatchCollection mc = reg.Matches(strHtml);
if (mc.Count > 0)
{
string[] strHref = new string[mc.Count];
int i = 0;
foreach (Match m in mc)
{
strHref[i] = m.Groups[1].Value;
++i;
}
return strHref;
}
return null;
}
string GetHttp(string strUrl)
{
string strHtml = "";
WebResponse wrp = null;
try
{
WebRequest wrq = WebRequest.Create(strUrl);
wrq.Timeout = 60000;
wrp = wrq.GetResponse();
}
catch (WebException e)
{
}
catch (Exception e)
{
}
finally
{
if (wrp != null)
{
StreamReader sr = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("GB2312"));
strHtml = sr.ReadToEnd();
sr.Close();
wrp.Close();
}
}
return strHtml;
}
可首先使用GetHttp获取指定URL的页面内容,然后将此内容作为参数传给GetLink,GetLink返回的String数组中的每个元素代表一个超链接。
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
string[] GetLink(string strHtml)
{
Regex reg = new Regex("href[//s//r]*=[//s//r]*[/"/']{0,1}([^/"/'//s//r>]*)[/"/'//s//r]{0,1}", RegexOptions.IgnoreCase);
MatchCollection mc = reg.Matches(strHtml);
if (mc.Count > 0)
{
string[] strHref = new string[mc.Count];
int i = 0;
foreach (Match m in mc)
{
strHref[i] = m.Groups[1].Value;
++i;
}
return strHref;
}
return null;
}
string GetHttp(string strUrl)
{
string strHtml = "";
WebResponse wrp = null;
try
{
WebRequest wrq = WebRequest.Create(strUrl);
wrq.Timeout = 60000;
wrp = wrq.GetResponse();
}
catch (WebException e)
{
}
catch (Exception e)
{
}
finally
{
if (wrp != null)
{
StreamReader sr = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("GB2312"));
strHtml = sr.ReadToEnd();
sr.Close();
wrp.Close();
}
}
return strHtml;
}
可首先使用GetHttp获取指定URL的页面内容,然后将此内容作为参数传给GetLink,GetLink返回的String数组中的每个元素代表一个超链接。
相关文章推荐
- .NET中获取HTML页面并提取其中的超链接
- 从html页面获取纯文本文件替换其中的内容
- 动态获取html页面的内容,并且取其中的某块元素的方法
- 动态获取html页面的内容,并且取其中的某块元素的方法
- html超链接href设置技巧和动态创建页面元素技巧
- 如何把html(form1)中的值用Submit传给serch.aspx页面,在serch.aspx又如何获取呢?(收集)
- c#正则表达式获取html超链接
- .NET获取Html字符串中指定标签的指定属性的值
- Android ios获取html页面的标签内容
- 纯html页面写的获取系统时间显示
- 前端-Html超链接返回上一个页面
- HTML页面获取URL参数
- 获取页面的HTML
- 从bodao_yishu.html页面中获取id,传到下一个museum.html页面中。
- 在html静态页面中获取请求参数和参数值(form)
- 如何在HTML页面中,用JavaScript获取application的值?
- .net 解决伪静态下,html页面无法访问
- 获取href超链接中的参数并把它们展示到页面上的input输入框中
- JS获取html页面上选中内容
- 一行JavaScript代码获取页面中的所有超链接地址