学习WebClient类 及Match.Groups 属性 保存网页所有超链接到本地

WebClient类

 

提供用于将数据发送到由 URI 标识的资源及从这样的资源接收数据的常用方法。

——命名空间:  System.Net

——WebClient 构造函数

初始化 WebClient 类的新实例。

——WebClient.Encoding 属性

获取和设置用于上载和下载字符串的 Encoding。

 

——常用方法

      1, WebClient.DownloadData(String)

       以Byte 数组形式通过指定的 URI 下载资源。

-语法

public byte[] DownloadData( string address)

 

-参数

address

    类型:System.String

    从中下载数据的 URI。

-返回值

类型:System.Byte[]

一个 Byte 数组,其中包含下载的资源。

 

   2,WebClient.DownloadFile 方法 (String, String)

将具有指定 URI 的资源下载到本地文件。

-语法

public void DownloadFile(

       string address,

       string fileName

)

 

-参数

address

    类型:System.String

    从中下载数据的 URI。

fileName

    类型:System.String

要接收数据的本地文件的名称。

 

 

 3,WebClient.DownloadString 方法 (String)

以 String 形式下载请求的资源。 以包含 URI 的 String 的形式指定要下载的资源。

-语法

public string DownloadString(

       string address

)

 

-参数

address

    类型:System.String

    包含要下载的 URI 的 String。

 

-返回值

类型:System.String

一个 String,其中包含请求的资源。

 

以下代码段实现功能,截取网页hao123上的超链接,并保存成文本:

static void Main(string[] args)
        {

            string addre = "http://www.hao123.com";
            WebClient wc = new WebClient();
            string html = wc.DownloadString(addre);    //获取所有内容到字符串 html中
            string reg = @"href=""(http://.+?)""";    //正则表达式,得到类似 <a href="http://caipiao.hao123.com/">的内容,加括号后实现分组功能
            MatchCollection mc = Regex.Matches(html, reg);
            foreach (Match item in mc)
            {
                File.AppendAllText(@"f:\httpAddre4.txt", (item.Groups[1].Value) + "\r\n");//通过正则表达式
                                                                                                      //加括号分组,把mc的值筛选后 得到http://caipiao.hao123.com/
                                                                                                    //放到文本文件中。
               
            }

简单说下Groups

Match.Groups 属性

获取由正则表达式匹配的组的集合。

语法:

public virtual GroupCollection Groups { get; }

属性值
类型:System.Text.RegularExpressions.GroupCollection
由模式匹配的字符组。

具体说明:正则表达式模式可以包含子表达式,这些子表达式是通过将正则表达式模式的一部分用括号括起来定义的。 每个这样的子表达式构成一个组。 例如,与北美电话号码匹配的正则表达式模式 (\d{3})-(\d{3}-\d{4}) 有两个子表达式。 第一组由区号构成,它包含电话号码的前三位数字。 此组由正则表达式的第一部分 (\d{3}) 捕获。第二组由单个电话号码组成,它包含电话号码的后七位数字。 此组由正则表达式的第二部分 (\d{3}-\d{4}) 捕获。

posted @ 2012-06-04 18:16  net515  阅读(946)  评论(0编辑  收藏  举报