NCrawler 是一款 .net 上的開源爬蟲,雖然它沒有arachnode.net那么成熟完善,但是代碼量小,設計結構好,很適合大家研讀。
在NCrawler.Demo項目下的Program.cs文件中,找到Main函數
函數開頭的一段代碼,是打開HTTP協議的限制(對同一個WEB最多同時發起兩個連接的限制)
ServicePointManager.MaxServicePoints = 999999; ServicePointManager.DefaultConnectionLimit = 999999; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.EnableDnsRoundRobin = true;
緊接着代碼進入一個demo的RUN() 函數:
SimpleCrawlDemo.Run();
該demo首先創建了一個Crawler對象,構造函數的第一個參數是初始爬的URL,后面的參數是一系列輸出的管道,以后講。
然后程序執行Crawl()函數開始爬行。
using (Crawler c = new Crawler(new Uri("http://ncrawler.codeplex.com"), new HtmlDocumentProcessor(), // Process html new iTextSharpPdfProcessor.iTextSharpPdfProcessor(), // Add PDF text extraction new GoogleLanguageDetection(), // Add language detection new Mp3FileProcessor(), // Add language detection new DumperStep()) { // Custom step to visualize crawl MaximumThreadCount = 2, MaximumCrawlDepth = 10, ExcludeFilter = Program.ExtensionsToSkip, }) { // Begin crawl c.Crawl(); }
這個函數完成了一系列配置,最后將URL添加到一個等待下載解析的URL序列m_CrawlerQueue中。代碼如下:
AddStep(m_BaseUri, 0);
在Crawl()函數中有一個專門用來處理 m_CrawlerQueue 的函數叫ProcessQueue()這個函數有一個重要的循環:
while (ThreadsInUse < MaximumThreadCount && WaitingQueueLength > 0) { StartDownload(); }
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。