环境
- 操作系统:ubuntu 16.04
- python版本:python2.7
爬虫架构
根据上面的流程,开始爬取百度百科1000个页面。
运行流程
很详细的说明。
我们要爬取的信息为
对应在html源码中的信息为:
知道了需要获取那些信息和爬虫的基本流程,
下面我们结合每一部分的功能来实现具体的代码。
爬虫调度端
启动爬虫,停止爬虫,或者监视爬虫的运行情况。
我们以百度百科python词条的url为入口。编写主函数。
# coding:utf8
import url_manager, html_parser, html_downloader,html_outputer
class SpiderMain(object):
def __init__(self):
self.urls = url_manager.UrlManager() #url管理器
self.downloader = html_downloader.HtmlDownLoader() #下载器
self.parser = html_parser.HtmlParser() #解析器
self.outputer = html_outputer.HtmlOutputer() #输出器
def craw(self,root_url):
count = 1
print "count =",count
#将入口url添加进url管理器(单个)
self.urls.add_new_url(root_url)
#启动爬虫的循环
while self.urls.has_new_url():
try:
#获取待爬取的url
new_url = self.urls.get_new_url()
print 'craw %d : %s'%(count,new_url)
#启动下载器下载html页面
htm