[心得] 重複抓特定html標籤資料

作者: felaray (傲嬌魚)   2013-06-19 13:07:09
前天開始研究RexExp,這東西令人惱羞.做了兩天以後才弄好想要的東西
所以在此分享給大家.語法為C#
說明:html是用HttpWebRequest抓出來的網頁資料,
目標是抓出<dt>...</dt>裡面的資料
string pattern = @"<dt[^>]*?>(?<word>.*?)</dt>";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(html);
int index = 0;
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
string x = groups["word"].Value.Trim();
if (x != "") //因為抓到不明空白,所以在此解決
Response.Write( x + "<BR>");
要條列序號的話就把++index加入上行
}
輸出資料
1: absolute bolometric magnitude 絕對熱星等
2: absolute zero 絕對零度,絕對零點
3: acceleration 加速度
4: acceleration of gravity 重力加速度
5: accretion 吸積
6: Achernar 水委一
7: achondrites 無球粒隕石
8: achromatic lens 消色差透鏡
9: albedo 反照率
10: Alcaid 搖光
11: Alcor 輔、開陽伴星
12: Alcyone 昂宿六
Html原始碼(節錄)
<dt><b>absolute zero 絕對零度,絕對零點 </b></dt>
作者: felaray (傲嬌魚)   2013-01-09 19:20:00
抱歉現在才看到回應 我後來的確是用那個解決XD
作者: s25g5d4 (function(){})()   2013-06-19 14:31:00
[^>]*?既然已用否定 就不要再下非貪婪 效能會減損
作者: felaray (傲嬌魚)   2013-06-19 14:54:00
好的 謝謝建議.目前來說是小資料所以還感受不到XD
作者: henry10423 (MrElsonXu)   2013-08-19 21:19:00
如果你用C#在做網頁解析時,建議可以用HtmlAgilityParser,這個東西挺強大的。不需要用Regex

Links booklink

Contact Us: admin [ a t ] ucptt.com