一个网络爬虫的Java实现.doc
文本预览下载声明
/FengYan/archive/2012/11/27/2788369.html#2566041
? ZeroCrawler V0.1是一只简单的多线程爬虫,其基本架构如下:
? ? ? 整个程序是这样运作的:Scheduler不断从Queue取出URL,如果发现可用的爬虫(空闲线程),那么就将URL分给一只爬虫。然后爬虫完成下载网页,抽取URL,保存网页的工作后就回归Scheduler(变回空闲线程)。直到Queue没有待爬取的URL,并且所有爬虫都空闲下来,就停止程序。
? ? ? Scheduler的主要工作就是建立线程池,从Queue中取出URL,分配URL给线程。容易出错的地方是退出条件。如果只是判断Queue为空就退出是不行的。因为这时可能还有爬虫在工作中,而它可能提取到新的URL加到Queue中。所以退出条件应该是Queue为空且线程池的线程全部空闲。Scheduler实现如下:
View Code
public static void Crawl(String url, String savePath) {
int cnt = 1;
long startTime = System.currentTimeMillis();
AtomicInteger numberOfThreads = new AtomicInteger(); //记录当前使用的爬虫数
ThreadPoolExecutor executor = new ThreadPoolExecutor(m_maxThreads, m_maxThreads,
3, TimeUnit.SECONDS, new LinkedBlockingQueueRunnable()); //建立线程池
Queue.Add(UrlUtility.Encode(UrlUtility.Normalizer(url))); //添加初始URL到Queue中
try {
while ((url = Queue.Fetch()) != null) {
executor.execute(new PageCrawler(url, savePath, numberOfThreads)); //将URL交给爬虫
while( (Queue.Size() == 0 numberOfThreads.get() != 0)
|| (numberOfThreads.get() == m_maxThreads) ) { //防止提前退出
sleep();
}
//if( cnt++ 1000 ) break;
if( Queue.Size() == 0 numberOfThreads.get() == 0 ) break;
}
} finally {
executor.shutdown();
}
long useTime = System.currentTimeMillis() - startTime;
System.out.println(use + Utility.ToStandardTime((int)(useTime / 1000)) + to finish + cnt + links);
System.out.println(remain url: + Queue.Size());
}
? ??Queue负责保存URL,判断URL重复出现与否。目前的保存方式是先使用Hash判断URL是否已经保存过,然后再将完整的URL整个保存到list中。从Queue中取出URL时使用广度优先原则。
View Code
public class Queue {
private static HashSetString m_appear = new HashSetString();
private static LinkedList
显示全部