程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 基於C#實現網絡爬蟲 C#抓取網頁Html源碼

基於C#實現網絡爬蟲 C#抓取網頁Html源碼

編輯:關於C語言

最近剛完成一個簡單的網絡爬蟲,開始的時候很迷茫,不知道如何入手,後來發現了很多的資料,不過真正能達到我需要,有用的資料--代碼很難找。所以我想發這篇文章讓一些要做這個功能的朋友少走一些彎路。

首先是抓取Html源碼,並選擇<ul class="post_list"> </ul>節點的href:要添加using System.IO;using System.Net;

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 private void Search(string url) { string rl; WebRequest Request = WebRequest.Create(url.Trim()); WebResponse Response = Request.GetResponse(); Stream resStream = Response.GetResponseStream(); StreamReader sr = new StreamReader(resStream, Encoding.Default); StringBuilder sb = new StringBuilder(); while ((rl = sr.ReadLine()) != null) { sb.Append(rl); } string str = sb.ToString().ToLower(); string str_get = mid(str, "<ul class=\"post_list\">", "</ul>"); int start = 0; while (true) { if (str_get == null) break; string strResult = mid(str_get, "href=\"", "\"", out start); if (strResult == null) break; else { lab[url] += strResult; str_get = str_get.Substring(start); } } } private string mid(string istr, string startString, string endString) { int iBodyStart = istr.IndexOf(startString, 0); //開始位置 if (iBodyStart == -1) return null; iBodyStart += startString.Length; //第一次字符位置起的長度 int iBodyEnd = istr.IndexOf(endString, iBodyStart); //第二次字符在第一次字符位置起的首次位置 if (iBodyEnd == -1) return null; iBodyEnd += endString.Length; //第二次字符位置起的長度 string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1); return strResult; } private string mid(string istr, string startString, string endString, out int iBodyEnd) { //初始化out參數,否則不能return iBodyEnd = 0; int iBodyStart = istr.IndexOf(startString, 0); //開始位置 if (iBodyStart == -1) return null; iBodyStart += startString.Length; //第一次字符位置起的長度 iBodyEnd = istr.IndexOf(endString, iBodyStart); //第二次字符在第一次字符位置起的首次位置 if (iBodyEnd == -1) return null; iBodyEnd += endString.Length; //第二次字符位置起的長度 string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1); return strResult; }

好了,上面就是全部代碼了,如果你想要運行出來的話,有些細節要自己修改下。

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved