溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發(fā)布時間:2020-06-24 18:29:45 來源:網(wǎng)絡 閱讀:443 作者:wdj_student 欄目:編程語言

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

 

  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.       } 

朋友們可以提取其他相關網(wǎng)站的新聞標題,但是提取的時候一定要記得找源代碼規(guī)律,因為

  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>"

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

希望大家可以根據(jù)程序來提取其他網(wǎng)站的內(nèi)容

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI