您的位置:首页 > 编程语言 > C#

C#开源爬虫NCrawler源代码解读以及将其移植到python3.2(1)

2013-06-26 22:15 696 查看
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);


第二个参数0表示初始深度,此时程序进入一个循环直到爬取到设定的深度为止。

在Crawl()函数中有一个专门用来处理 m_CrawlerQueue 的函数叫ProcessQueue()这个函数有一个重要的循环:

while (ThreadsInUse < MaximumThreadCount && WaitingQueueLength > 0)
			{
				StartDownload();
			}


在StartDownload()函数的内部就是启用了线程池技术,下载网页并解析。并且在线程完成后回调,继续处理序列.


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: