zoukankan      html  css  js  c++  java
  • 正则表达式与抓取是网页图片

    正则表达式

    命名空间: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();

    }
  • 相关阅读:
    C++ XML解析之TinyXML篇[转]
    TinyXML:一个优秀的C++ XML解析器[转]
    nginx 出现413 Request Entity Too Large问题的解决方法
    redis配置认证密码
    《Discuz安装时候出现乱码 -- 问题解决方法》
    MySQL创建用户与授权
    CentOS 7 安装mysql
    setfacl命令 来自: http://man.linuxde.net/setfacl
    install pip3 for python 3.x
    自己制作ssl证书:自己签发免费ssl证书,为nginx生成自签名ssl证书
  • 原文地址:https://www.cnblogs.com/Kingly/p/2741617.html
Copyright © 2011-2022 走看看