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

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



                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱知菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值