C#從新浪新聞上提取新聞標題

 下面我以新浪軍事新聞模塊提取軍事新聞的標題,將提取到的新聞標題保存到記事本上

 

  1. static void Main(string[] args) 
  2.       { 
  3.           Stopwatch watch = new Stopwatch(); 
  4.           watch.Start(); 
  5.           WebClient wc = new WebClient(); 
  6.           int count = 0; 
  7.           //正則表達式 
  8.           string regLinks = "<li><a\\s+href=\"http://mil.news.sina.com.cn/20\\d{2}-\\d{2}-\\d{2}/\\d{10}\\.html\"\\s+target=\"_blank\">(.+?)</a><span\\s+class=\"time\">(.+?)</span></li>"
  9.           //由於耗時太久,在這裏我只提取新浪100個頁面的新聞標題 
  10.           for (int i = 1; i < 100; i++) 
  11.           { 
  12.               //http://roll.mil.news.sina.com.cn/col/zgjq/index_4.shtml 
  13.               string url = @"http://roll.mil.news.sina.com.cn/col/zgjq/index_"+i+".shtml"
  14.  
  15.               string html = wc.DownloadString(url); 
  16.               MatchCollection matchs = Regex.Matches(html, regLinks); 
  17.               using (StreamWriter sw = new StreamWriter(@"c:\news.txt"true, Encoding.GetEncoding("gb2312"))) 
  18.               { 
  19.                   foreach (Match match in matchs) 
  20.                   { 
  21.                       if (match.Success) 
  22.                       { 
  23.                           sw.WriteLine(match.Groups[1].Value + "\t" + match.Groups[2].Value); 
  24.                           count++; 
  25.                       } 
  26.                   } 
  27.               } 
  28.           } 
  29.           watch.Stop(); 
  30.           Console.WriteLine("共提取了{0}個新聞標題",count); 
  31.           Console.WriteLine("共計用時:{0}",watch.Elapsed); 
  32.           Console.ReadKey(); 
  33.       } 

朋友們可以提取其他相關網站的新聞標題,但是提取的時候一定要記得找源代碼規律,因爲

  1. //正則表達式 
  2. string regLinks = "<li><a\\s+href=\"http://mil.news.sina.com.cn/20\\d{2}-\\d{2}-\\d{2}/\\d{10}\\.html\"\\s+target=\"_blank\">(.+?)</a><span\\s+class=\"time\">(.+?)</span></li>"

正則表達式的拼接是根據標題源代碼的規律來提取的,如果不找規律,是很難進行提取的。

希望大家可以根據程序來提取其他網站的內容

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章