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();

            }

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

  • 相关阅读:
    位运算
    LeetCode(230):二叉树中的第K小元素
    LeetCode(69):二分法求平方根
    TCP如何保证传输可靠性
    2种方法(递归+BFS)求二叉树的最小/最大深度
    自动生成Mapper文件(基于Mybatis Maven插件)
    Git的使用
    Java关键字及其作用详解
    Vagrant安装Centos/7
    java servlet 几种页面跳转的方法及传值
  • 原文地址:https://www.cnblogs.com/tony-brook/p/7803272.html
Copyright © 2011-2022 走看看