Python 爬取百度Python词条
1.main.py(运行)
# -*- coding: utf-8 -*-
from baiKe_spider import url_manager, html_downloader, html_parser,html_outputer
#初始化需要的对象
class SpiderMain(object):
def __init__(self):
self.urls = url_manager.UrlManager() #url管理器
self.downloader = html_downloader.HtmlDownloader() #下载器
self.parser = html_parser.HtmlParser() #html解析器
self.outputer = html_outputer.HtmlOutputer() #html输出器
#爬出的调度程序
def craw(self, root_url):
count = 1
self.urls.add_new_url(root_url);
while self.urls.has_new_url():
try:
new_url = self.urls.get_new_url() #获取新的url
print 'craw %d:%s' % (count,new_url)
html_cont = self.downloader.dowmload(new_url) #启动下载器下载页面
new_urls,new_data = self.parser.parse(new_url,html_cont) #解析器
self.urls.add_new_urls(new_urls)
self.outputer.cllect_data(new_data)
#获取1000个之后跳出循环
if count == 1000:
break
count = count+1
except:
print 'craw failed'
self.outputer.output_html()
if __name__ == "__main__":
root_url = "https://baike.baidu.com/item/Python" #入口的url(根据要爬取的地址)
obj_spider = SpiderMain()
obj_spider.craw(root_url) #启动爬虫
2.url_manager.py(URL管理器)
# -*- coding: utf-8 -*-
class UrlManager(object):
def __init__(self):
self.new_urls = set()
self.old_urls = set()
#向管理器里添加一个新url
def add_new_url(self,url):
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
self.new_urls.add(url)
#向管理器里批量添加多个新url
def add_new_urls(self,urls):
if urls is None or len(urls) == 0:
return
for url in urls:
self.add_new_url(url)
#判断管理器中是否有新的待爬取的url
def has_new_url(self):
return len(self.new_urls) != 0
#获取一个待爬去的url
def get_new_url(self):
new_url = self.new_urls.pop()
self.old_urls.add(new_url)
return new_url
3.html_parser.py(html解析器)
# -*- coding: utf-8 -*-
import urlparse
from bs4 import BeautifulSoup
import re
import urllib
class HtmlParser(object):
def _get_new_urls(self, page_url, soup):
new_urls = set()
#/item/*
links = soup.find_all('a',href = re.compile(r"^/item/"))#根据网站的格式变化
for link in links:
new_url = link['href']
# new_url.split("/")
new_full_url = urlparse.urljoin(page_url, new_url)
# new_url1 = urllib.unquote(so).decode('gbk').encode('utf-8')
new_urls.add(new_full_url)
return new_urls
def _get_new_data(self, page_url, soup):
#声明一个字典
res_data = {}
#url
res_data['url'] =page_url
#
4.html_outputer.py(html输出器)
# -*- coding: utf-8 -*-
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def cllect_data(self,data):
if data is None:
return
self.datas.append(data)
def output_html(self):
fout = open('output.html','w')
fout.write("")
fout.write("
5.html_downloader.py(html下载器)
# -*- coding: utf-8 -*-
import urllib2
class HtmlDownloader(object):
def dowmload(self,url):
if url is None:
return None
response = urllib2.urlopen(url)
if response.getcode() != 200:
return None
return response.read()