python 实现简单爬虫

SpiderMain类

SpiderMain是整个爬虫的驱动类

主要做了以下几件事
1.初始化url管理器,初始化html下载器,初始化html分析器,初始化输出器
2.实现craw方法

craw方法

它有一个参数root_url

首先将root_url加入到url管理器中,然后进行循环直到管理器中不再有新的url为止,然后输出收集的数据
在循环中首先得到新的url,然后用html下载器下载html页面,然后用parser对html内容进行解析得到其中的urls集合和数据
将新的urls加入到url管理器中,数据加入到输出器中这里用try语句输出错误信息

SpiderMain类代码

# coding:utf8
from pachong.baike_spider import url_manager, html_downloader, html_parser, html_outputer


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 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()
                print("craw %d : %s" % (count, new_url))
                html_cont = self.downloader.download(new_url)
                new_urls, new_data = self.parser.parse(new_url, html_cont)
                self.urls.add_new_urls(new_urls)
                self.outputer.collect_data(new_data)

                if count == 10:
                    break

                count = count + 1
            except Exception as e:
                print(str(e))

        self.outputer.output_html()


if __name__ == "__main__":
    root_url = "https://baike.baidu.com/item/Python/407313"
    obj_spider = SpiderMain()
    obj_spider.craw(root_url)


UrlManager类

UrlManager是对url进行管理的类

它主要通过两个集合来对url进行管理
new_urls中存放新的url
old_urls中存放就的url以防造成死循环

add_new_url方法

这个方法有一个参数url如果其为None则直接返回,如果url不在新url集合中也不在旧url集合中则将其加到新url的集合中

UrlManager代码

# coding:utf8

class UrlManager(object):
    def __init__(self):
        self.new_urls = set()
        self.old_urls = set()

    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_urls(self, urls):
        if urls is None or len(urls) == 0:
            return
        for url in urls:
            self.add_new_url(url)

    def has_new_url(self):
        return len(self.new_urls) != 0

    def get_new_url(self):
        new_url = self.new_urls.pop()
        self.old_urls.add(new_url)
        return new_url


HtmlDownloader类

该类是用来下载html页面的
这里因为还不熟悉requests库所以用的是urllib,这里用urlopen来请求对应url

HtmlDownloader代码

# coding:utf8

from urllib import request


class HtmlDownloader(object):
    def download(self, url):
        if url is None:
            return None
        res = request.urlopen(url)
        if res.getcode() != 200:
            return None
        return res.read()


HtmlParser类

该类利用BeautifulSoup解析html

1.首先生成BeautifulSoup对象
2.利用1中对象解析出该页面的url,这里需要分析页面的结构,利用re模块进行正则表达式的匹配,最后利用urllib生成完整的url
3.利用1中对象解析出一张数据表

HtmlParser代码

# coding:utf8

import re
import urllib.parse
from bs4 import BeautifulSoup


class HtmlParser(object):
    def parse(self, page_url, html_cont):
        if page_url is None or html_cont is None:
            return

        soup = BeautifulSoup(html_cont, 'html.parser', 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()

        # format /item/....
        links = soup.find_all('a', href=re.compile(r'/item/'))
        #print(links)
        for link in links:
            new_url = link['href']
            new_full_url = urllib.parse.urljoin(page_url, new_url)
            new_urls.add(new_full_url)
            #print(new_full_url)
        return new_urls

    def _get_new_data(self, page_url, soup):
        res_data = {'url': page_url}

        # <dd class="lemmaWgt-lemmaTitle-title"> <h1>Python</h1>
        title_node = soup.find('dd', class_='lemmaWgt-lemmaTitle-title').find('h1')
        res_data['title'] = title_node.get_text()

        # <div class="lemma-summary" label-module="lemmaSummary">
        summary_node = soup.find('div', class_='lemma-summary')
        res_data['summary'] = summary_node.get_text()
        return res_data

HtmlOutputer类

这是输出数据的类

目的是组织数据,注意编码

HtmlOutputer代码

# coding:utf8

class HtmlOutputer(object):
    def __init__(self):
        self.datas = []

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

    def output_html(self):
        fout = open('output.html', 'w', encoding='utf-8')

        fout.write('<html>')
        fout.write("<head><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"></head>")
        fout.write('<body>')
        fout.write('<table>')

        for data in self.datas:
            fout.write('<tr>')
            fout.write('<td>%s</td>' % data['url'])
            fout.write('<td>%s</td>' % data['title'])
            fout.write('<td>%s</td>' % data['summary'])
            fout.write('</tr>')

        fout.write('</table>')
        fout.write('</body>')
        fout.write('</html>')

        fout.close()

posted @ 2018-04-12 23:22  lan126  阅读(222)  评论(0编辑  收藏  举报