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

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

2013-06-27 10:16 246 查看
在上一篇中,我们提到了管道这个概念(pipeline),其实所有的管道都实现了同一接口叫

public interface IPipelineStep
{
void Process(Crawler crawler, PropertyBag propertyBag);
}


所有爬到的网址都将被 构造 Crawler 时通过构造函数注入的管道 处理。

一般来说第一个处理的管道是 HtmlDocumentProcessor,它负责解析网页。那么其实现接口的具体函数就很值得一看。

在函数的开始处NCrawler使用了AOP技术做了一次参数的非空检查,使用的AOP框架是轻量级的,叫 AspectF

AspectF.Define.
NotNull(crawler, "crawler").
NotNull(propertyBag, "propertyBag");


紧接着函数进行了一系列操作,把HTML的文本,包括 title , meta 提取出来,找出其中 links ,然后开启循环针对里面每个 link 整形重新添加到 爬虫的 等待爬行的URL的序列,代码如下:

foreach (string link in links.Links.Union(links.References))
{
if (link.IsNullOrEmpty())
{
continue;
}

string decodedLink = ExtendedHtmlUtility.HtmlEntityDecode(link);
string normalizedLink = NormalizeLink(baseUrl, decodedLink);
if (normalizedLink.IsNullOrEmpty())
{
continue;
}

crawler.AddStep(new Uri(normalizedLink), propertyBag.Step.Depth + 1,
propertyBag.Step, new Dictionary<string, object>
{
{Resources.PropertyBagKeyOriginalUrl, link},
{Resources.PropertyBagKeyOriginalReferrerUrl, propertyBag.ResponseUri}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐