1.有url獲取到網頁源代碼:html
using System.Web; using System.IO; using System.Net; private void GetHtmlinfo(string PageUrl) { WebRequest request = WebRequest.Create(PageUrl); WebResponse response = request.GetResponse(); Stream resStream = response.GetResponseStream(); StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8); string htmlinfo = sr.ReadToEnd(); resStream.Close(); sr.Close(); }
2.獲取標籤中的值:url
using System.Text.RegularExpressions; /// 獲取字符中指定標籤的值 /// </summary> /// <param name="str">字符串</param> /// <param name="title">標籤</param> /// <returns>值</returns> public static string GetTitleContent(string str, string title1, string title2) { string tmpStr = string.Format("<{0}[^>]*?>(?<Text>[^<]*)</ {1}>", title1, title2); //獲取<title>之間內容 Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase); string result = TitleMatch.Groups["Text"].Value; return result; }
Example:
HTML 源文件:<span class="t1_tx">現排名:<b class="color1">20</b>spa
Parameter: title1 = @"span class=""t1_tx"">現排名:<b class=""color1""";code
title2 - "b";orm
3.獲取標籤中的屬性:htm
/// 獲取字符中指定標籤的值 /// </summary> /// <param name="str">字符串</param> /// <param name="title">標籤</param> /// <param name="attrib">屬性名</param> /// <returns>屬性</returns> public static string GetTitleContent(string str, string title,string attrib) { string tmpStr = string.Format("<{0}[^>]*?{1}=(['\"\"]?)(?<url>[^'\"\"\\s>]+)\\1[^>]*>", title, attrib); //獲取<title>之間內容 Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase); string result = TitleMatch.Groups["url"].Value; return result; }