C# 截取所需网页上的部分内容

比如我有一个test.html,其内容如下:  

 

我要获得OnlyClass下标签Span的内容和标签a中的正文内容。

目前我了解的方法有3种。

1、利用正则表达式(在此不做具体说明)
2、如果能够找到唯一的字符标识,可以利用截取的方式。
3、利用外部HtmlAgilityPack.dll

方法2的实现:

WebRequest myWebRequest = WebRequest.Create( @"D:\\test.htm");
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream myStream = myWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader myStreamReader = new StreamReader(myStream, encode);
string html = myStreamReader.ReadToEnd();

List nameList = new List();
List textList = new List();

 string s = html.Replace("\r", string.Empty);
 s = s.Replace("\n", string.Empty);
 s = s.Replace("\t", string.Empty);

 string[] SPLIT_CLASS_NAME = new string[] { "class=\"only\">" };

 string[] strArray = s.Split(SPLIT_CLASS_NAME, StringSplitOptions.None);
 string[] SPLIT_SPAN = new string[] { "" };

 int index = 0;

 foreach (var item in strArray)
 {
     if (index== 0)
     {
         index++;
         continue;
     }

     int tmpIndex = item.IndexOf('>');
     string tmp = item.ToString();
     tmpIndex = tmp.IndexOf("", string.Empty));
     }
 }

方法3的实现:

下载HtmlAgilityPack.dll,并引用到工程中。

 	    HtmlWeb htmlWeb = new HtmlWeb();
            HtmlAgilityPack.HtmlDocument document = htmlWeb.Load("D:\\test.htm");
            string xpath = "//ul[@class='onlyClass']//li/a";
            HtmlNodeCollection collection = document.DocumentNode.SelectNodes(xpath);
	    List nameList = new List();
            List textList = new List();
            foreach (HtmlNode item in collection)
            {
                HtmlNode temp = null;
                string name = null;
                string text = null;
                temp = HtmlNode.CreateNode(item.OuterHtml);
                if (string.IsNullOrEmpty(temp.InnerText) == false)
                {
                    name= temp.SelectSingleNode("//span[@class='only']").InnerText;
                    text = temp.InnerText;
                }

                if (name != null && text != null)
                {
                    nameList.Add(name);
                    textList.Add(text);
                }
            }


 

你可能感兴趣的:(C#)