/
spider_main.py
34 lines (34 loc) · 1.22 KB
/
spider_main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#coding:utf-8
import url_manager,html_downloader,html_parser,html_outputer
import time
class SpiderMain(object):
def __init__(self):
self.urls = url_manager.UrlManager()
self.downloader = html_downloader.HtmlDownloader()
self.parser = html_parser.HtmlParser()
self.outputer = html_outputer.HtmlOutputer()
def crawl(self, root_url):
self.urls.add_new_url(root_url)
count = 1
try:
while self.urls.has_new_url():
new_url = self.urls.get_new_url()
content = self.downloader.download(new_url)
new_urls, new_data = self.parser.parse(new_url, content)
self.urls.add_new_urls(new_urls)
self.outputer.collect_data(new_data)
print count, new_url
if count > 20:
break
count += 1
except Exception,e:
print e
print "download fail"
self.outputer.output_html()
if __name__ == "__main__":
start = time.time()
root_url = "http://baike.baidu.com/view/21087.htm"
object_spider = SpiderMain()
object_spider.crawl(root_url)
end = time.time()
print "cost all time: %s" % (end-start)