from:http://www.dotblogs.com.tw/yilinliu/archive/2009/03/13/7470.aspx
作用:取得HTML或XML內容中,某個標籤下所指定的屬性值。
輸入參數:
- strHtml(string):HTML或XML的內容。
- strTagName(string):標籤名。
- strAttributeName(string):屬性名。
public static string[] GetAttribute(string strHtml, string strTagName, string strAttributeName)
{
List<string> lstAttribute = new List<string>();
string strPattern = string.Format("<\\s*{0}\\s+.*?(({1}\\s*=\\s*\"(?<attr>[^\"]+)\")|({1}\\s*=\\s*'(?<attr>[^']+)')|({1}\\s*=\\s*(?<attr>[^\\s]+)\\s*))[^>]*>"
, strTagName
, strAttributeName);
MatchCollection matchs = Regex.Matches(strHtml, strPattern, RegexOptions.IgnoreCase);
foreach (Match m in matchs)
{
lstAttribute.Add(m.Groups["attr"].Value);
}
return lstAttribute.ToArray();
}
//要抓取的網頁
string Url = "http://www.gov.tw/";
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(Url);
using (HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse())
{
//判斷是否有指定編碼(預設用codepage=950)
Encoding encPage = webResp.ContentType.IndexOf("utf-8", StringComparison.OrdinalIgnoreCase) > 0 ? Encoding.UTF8 : Encoding.GetEncoding(950);
using (StreamReader reader = new StreamReader(webResp.GetResponseStream(), encPage))
{
string strContent = reader.ReadToEnd();
//列出所有<img>裡的src屬性值
string[] aryValue = GetAttribute(strContent, "img", "src");
for (int i = 0; i < aryValue.Length; i++)
{
Console.WriteLine(aryValue[i]);
}
}
}