美文网首页
python基础爬虫组成

python基础爬虫组成

作者: 留思 | 来源:发表于2019-02-17 17:10 被阅读0次

基础爬虫的组成部分

python基础爬虫由五部分组成,分别是URL管理器、HTML下载器、HTML解析器、数据存储器以及爬虫调度器。

1、URL管理器

实现思路:

1、设置未爬取和已爬取的URL集合;

2、判断是否有未爬取的URL;

3、获取一个未爬取的URL

4、将新的URL添加到未爬取的URL集合中;

5、获取未爬取和已爬取的URL集合大小;

#看下面一个例子
# -*- coding: utf-8 -*-
class UrlManager(object):
    """docstring for UrlManager"""
    def __init__(self):
        self.new_urls = set()#未爬取URL集合
        self.old_urls = set()#已爬取URL集合
    def has_new_url(self):
        """
        判断是否有未爬取的URL
        :return
        """
        return self.new_urls_size()!=0

    def get_new_url(self):
        new_url = self.new_urls.pop()
        self.old_urls.add(new_url)
        return new_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)

    def add_new_url(self,urls):
        if urls is None or len(urls)==0:
            return 
        for url in urls:
            self.add_new_url(url)

    def new_url_size(self):
        return len(self.new_urls)
        
    def old_url_size(self):
        return len(self.old_urls)

2、HTML下载器

用于下载网页,注意网页的编码,下载器需要用到Requests模块

# -*- coding: utf-8 -*-
import requests
class HtmlDownloader(object):
    """docstring for HtmlDownloader"""
    def download(self, url):
        if url is None:
            return None
        user_agent = 'Mozilla/4.0(compatible;MSTE 5.5; Windows NT)'
        headers = {'User-Agent':user_agent}#模拟浏览器访问
        r = requests.get(url,headers= headers) 
        if r.status_code == 200:
            r.encoding = 'utf-8'
            return r.text
        return None

3、HTML解析器

用BeautifulSoup4进行HTML解析,以百度百科词条为例

# -*- coding: utf-8 -*-
import re
import urlparse
from bs4 import BeautifulSoup

class HtnlPareser(object):
    """docstring for HtnlPareser"""
    def pareser(self, page_url,html_cont):
        if page_url is None or html_cont is None:
            return
        soup = BeautifulSoup(html_cont,'html.pareser',from_encoding = 'utf-8')
        new_urls = self._get_new_urls(page_url,soup)
        new_data = self._get_new_data(page_url,soup)
        return new_urls,new_data
    def _get_new_urls(self,page_url,soup):
        new_urls=set()
        #抽取符合要求的a标记
        links = soup.find_all('a',href=re.compile(r'/view/\d+\.htm'))
        for link in links:
            new_url = link['href']
            new_full_url = urlparse.urljoin(page_url,new_url)
            new_url.add(new_full_url)
        return new_urls
        

    def _get_new_data(self,page_url,sopu):
        data = {}
        data['url']=page_url
        title = soup.find('dd',class_='lemmaWgt-lemmaTitle-title').find('h1')
        data['title']=title.get_text()
        summary = soup.find('div',class_='lemma-summary')
        data['summary']=summary.get_text()
        return data

4、数据存储器

数据存储器主要包括两个方法:stroe_data(data)用于将解析出来的数据存储在内存中,output_html用于将存储的数据输出为指定的文件格式,我们使用的是将数据输出为HTML格式

# -*- coding: utf-8 -*-
import codecs
class DataOutput(object):
    """docstring for DataOutput"""
    def __init__(self):
        self.datas=[]

    def syore_data(self,data):
        if data is None:
            return
        self.datas.append(data)

    def output_html(self):
        fout = codecs.open('baike.html','w',encoding='utf-8')
        fout.write("<html>")
        fout.write("<head><meta charset='utf-8'/></head>")
        fout.write("<body>")
        fout.write("<table>")
        for data in self.datas:
            fout.write("<tr>")
            fout.write("<td>%</td>"%data['url'])
            fout.write("<td>%</td>"%data['title'])
            fout.write("<td>%</td>"%data['summary'])
            fout.write("</tr>")
            self.datas.remove(data)
        fout.write("</table>")
        fout.write("</body>")
        fout.write("</html>")

5、爬虫调度器

爬虫调度器首先要做的是初始化各个模块,然后再内部实现按照流程控制各个模块工作。以下是爬取百度百科的爬虫控制器

# -*- coding: utf-8 -*-
from DataOutput import DataOutput
from HtmlDownloader import HtmlDownloader
from HtmlPareser import HtmlPareser
from UrlManager import UrlManager

class SpiderMan(object):
    """docstring for SpiderMan"""
    def __init__(self):
        self.manager = UrlManager()
        self.downloader = HtmlDownloader()
        self.parser = HtmlPareser()
        self.output = DataOutput()

    def crawl(self,root_url):
        self.mannager.add_new_url(root_url)
        while(self.manager.has_new_url() and self.manager.old_url_size()<100):
            try:
                new_url = self.manager.get_new_url()
                html = self.downloader.download(new_url)
                new_url,data = self.parser.parser(new_url,html)
                self.manager.add_new_url(new_urls)
                self.output.store_data(data)
                print("已经抓取%s个链接"%self.manager.old_url_size())

            except Exception:
                print ("crawl failed")
        self.output.output_html()

if __name__ == '__main__':
    spider_man = SpiderMan()
    sprder_man.crawl('http://baike.baidu.com/view/284853.html')

相关文章

网友评论

      本文标题:python基础爬虫组成

      本文链接:https://www.haomeiwen.com/subject/qsogeqtx.html