C#使用正则表达式把相对地址转化为绝对地址
本文就应用C#的正则表达式来获取URL,并转化为绝对路径,请看下面实现的方法。 基本思路: 1、先用正则得到所有的页面源码中所有的url, 可以参考这个 (?=href\s*=)(?:[ \s""']*)(?!#|mailt
本文就应用C#的正则表达式来获取URL,并转化为绝对路径,请看下面实现的方法。
基本思路:
1、先用正则得到所有的页面源码中所有的url,
可以参考这个
(?<=href\s*=)(?:[ \s""']*)(?!#|mailto|location.|javascript|.*css|.*this\.)[^""']*(?:[ \s>""'])
得到的值可能如下:
"/company/list.aspx"
"http://www.sohu.com/index.html"
..
2、然后再拼接加上前缀,这个前缀就是你的页面的根目录,之前就已经知道的。
大概写了个简单例子:获取页面内容部分省略了·! 网上资源很多。

public static void Main(string[] args) { string minHtml = string.Empty; string url = @"http://www.agronet.com.cn/default.aspx"; string preurl = url.Remove(url.IndexOf('/', 8) 1);//获取url的根目录地址 minHtml = GetRequestString(url, 6000, 1, System.Text.Encoding.UTF8);//获取指定页面的内容 Console.WriteLine(preurl); GetUrlListBHtml(minHtml,preurl); Console.ReadKey(); } /// <summary> /// 获取html内容中的相对url地址,并向相对地址添加前缀 /// </summary> /// <param name="text">html内容</param> /// <param name="pre">要添加的绝对地址前缀</param> public static void GetUrlListBHtml(string text,string pre) { string pat = @"(?<=href\s*=)(?:[ \s""']*)(?!#|mailto|location.|javascript|.*css|.*this\.)[^""']*(?:[ \s>""'])"; // Compile the regular expression. System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(pat, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Match the regular expression pattern against a text string. System.Text.RegularExpressions.Match m = r.Match(text); int matchCount = 0; while (m.Success) { string urlX=m.Value.Replace("\"","");//替换引号 if (urlX.IndexOf("/") == 0)//相对地址 { matchCount ; Console.WriteLine("第" matchCount "个相对地址:"); Console.WriteLine("原地址是" urlX); Console.WriteLine("新的绝对地址是" pre urlX); Console.WriteLine("------------------------------------"); } m = m.NextMatch(); } }
收藏文章
精彩图集
精彩文章
- 暂无记录。
热门标签
自动提交
面向对象
BOOST
批量转换
桌面
Innodb表
之死
comparator
ConfigParser
文件哈
imei
textbox
linux解压缩
MySQL创建用户
radiobutton
表单数据丢
catch
访问外部变量
运行机制
microtime
生成Json数据
Execl导出
字符串查找
xcacls.vbs
post方法
邮箱激
边框
取值
setup.py
md5_file
newFunction(
mysql:
授权
fun
ls命令
切换图片
Media
类型格式转换
mysqlbinlog
多说
拦截外拨电话
apache配置文件
mytop
文件扩展名
远程页面
列索引
target=_b
短信
生成随机数
services
本地服务
messagebox
执
sql数据库表
建造者模式
addslashes函数
变为
中断锁定
导出数据
pyqt
赞助商链接
@CopyRight 2002-2008, 1SOHU.COM, Inc. All Rights Reserved QQ:1010969229