我使用simplecrawler
制作了一个简单的爬虫:D
它的构造函数有一个集合对象,其中保存访问过的 URL:
this.visited = new Set();
任何无效的 URL 都将添加到此处:
this.visited.add(url);
目前,当新的 url 添加到队列中时,我会检查它是否被访问:
if (this.visited.has(newURL))
我可以在此设置对象中使用正则表达式来阻止来自特定站点的网址,如下所示吗?
// to block www.xxx.com/123, www.xxx.com/456, www.xxx.com/789
this.visited.add('/www\.xxx\.com\/\d/g');
if (this.visited.has(givenURL))
// do not visit
else
// visit
如果可以做到这一点,完成这件事的最佳方法是什么?
最佳答案
您可以循环遍历集合并检查 URL 是否与集合中的项目匹配:
this.visited = new Set();
var BreakException = {};
this.visited.add('www\\.xxx\\.com/\\d+');
this.visited.add('www.xxx.com/123')
try {
this.visited.forEach(function(x) {
if ('www.xxx.com/123'.match(new RegExp(x))) {
var visited = true;
throw BreakException;
}
});
} catch (e) {
// do not visit
}
if (visited) {
// visit
}
注意我添加到集合中的 URL。您在问题中使用的那个不起作用。
您必须抛出异常才能中断循环,因为 Array.forEach
不支持 break;
。
关于javascript - 将正则表达式存储在集合对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054622/