zoukankan      html  css  js  c++  java
  • 使用WebClient下载网页,用正则匹配需要的内容

    WebClient是一个操作网页的类

    webClient web=new  WebClient();

    web.DownloadString(网页的路径,可以是本地路径);--采用的本机默认的编码格式  返回值为string
    如果网页采用用的是utf8的话用   web.DownloadData(与DownloadString用法一样) 的返回值为byte[](字节数组)

    一个简单的匹配图片下载的代码:

    static void Main(string[] args)

            {

                //操作网页的一个类

                WebClient web = new WebClient();

                //<img src="https://gss3.bdstatic.com/84oSdTum2Q5BphGlnYG/timg?wapp&amp;quality=80&amp;size=b65_65&amp;subsize=20480&amp;cut_x=0&amp;cut_w=0&amp;cut_y=0&amp;cut_h=0&amp;sec=1369815402&amp;srctrace&amp;di=9f6cdc0624f7b25832f34ad393db5063&amp;wh_rate=null&amp;src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fpic%2Fitem%2Fe824b899a9014c084548ecd9087b02087bf4f45f.jpg"/>

                byte[] buffer = web.DownloadData(@"https://tieba.baidu.com/f?kw=%E5%A5%BD%E7%9C%8B%E7%9A%84%E5%9B%BE%E7%89%87&fr=fenter&prequery=%E5%A5%BD%E7%9C%8B%E7%9A%84%E5%9B%BE%E7%89%87%E5%A4%A7%E5%85%A8%E5%B8%A6%E5%AD%97");

                //将字节转换成字符串,该网页采用的是utf8编码格式

                string html = Encoding.UTF8.GetString(buffer);

                MatchCollection mc = Regex.Matches(html, @"<img.+?(?<priSrc>https.+?.jpg).+?>");

                int i = 0;

                foreach (Match item in mc)

                {

                    i++;

                    Console.WriteLine(item.Value);

                    string uri = item.Groups["priSrc"].Value;

                    string path = Path.Combine(@"C:UsersAdministratorDesktopimages", +i+".jpg");

                                //用DownloadFile下载文件

                    web.DownloadFile(uri, path);

                }

              

                Console.ReadKey();

            }

    读取之后转化为字符串(自己转把,不写了)就能把网页拿过来搞事情了

  • 相关阅读:
    设计模式笔记——策略模式(Strategy Pattern)
    C#基础笔记——集合和LINQ
    C#基础笔记——命名规范
    C#基础笔记——语言基础
    C#基础笔记——代码整洁
    C#基础笔记——序列化(Serialize)和反序列化(NonSerialize)
    C#基础笔记——资源管理
    C#基础笔记——协变(Covariance)和逆变(Contravariance)
    C#基础笔记——委托(Delegate)和事件(Event)
    C#基础笔记——泛型(Genericity)
  • 原文地址:https://www.cnblogs.com/tony-brook/p/7803272.html
Copyright © 2011-2022 走看看