正则表达式与抓取是网页图片

正则表达式

命名空间:using System.Text.RegularExpressions;

常用的类:

Regex

MatchCollection

Match

Group

GroupCollection

常用的方法:

Regex.IsMatch(); 返回值bool

Regex.Match(); 返回值Match

Regex.Matches(); 返回值MatchCollection

Regex.Replace(); 返回值string

正则表达式抓取图片:

引用命名空间:using System.Net;

using System.IO;

做题思想:1》首先从网上获取网页上的所有信息,2》使用正则表达式进行匹配获得,想要得到的图片的具体地址,3》下载;

static void Mian(string[] args)

{

WebClient wc=new WebClient();

string html=wc.DownloadString(@"网---页---地---址");

MatchCollect mc=Regex.Matches(html, @"<\s?img[^>]+src=""([^""]+)""");//使用正则表达式进行匹配,因为所获的图片较多,所以常见一个List集合储存;

List<string> pic=new List<string>();

foreach(Match m in mc)//进行遍历

{

if(m.Success)//若是能够匹配的字符串放到pic集合中

{

pic.Add(m.Group[1].Value.Trim());//获得图片 src="~~~"的形式;提取图片名称

}

}

string url=@"网页地址";

for(int i=0;i<pic.Count;i++)

{

string temp=pic[i];

temp = url+ / + temp; //往图片名称前添加url地址;

pic[i]=temp; //重新改变pic集合中的图片名称,到此此图片就是一个完整的网页图片地址

}

string address="想要下载到的目标位置";

if(!Directory.Exists(address)) //先进行判断磁盘中是否有要用的文件夹,没有则创建

{

Directory.CreateDirectory("文件");

}

else

{

for(int i=0;i<pic.Count.i++)

{

string name=Regex.Match(pic[i],@"./(.+)").Groups[1].Value;

//Regex.Match(pic[i],@"./(.+)"); 进行匹配,显示图片名称 "/~~~"的形式;

//Regex.Match(pic[i],@"./(.+)").Groups[1].Value 抓取图片名称,这是为了在下载时创建出的名字与网上名字一样;

wc.DownloadFile(pic[i],path.Combine(address,name);//下载完成

}

}

Console.ReadKey();

}
posted on 2012-10-26 18:00  Kingly  阅读(625)  评论(0编辑  收藏  举报