记一个爬虫实例

1. 提出需求

刚学会爬虫,写一个从别的教程看来的爬虫。

2. 分析阶段

打开要爬取的网站,查看要爬取的节点的特点。
这里不上图了,直接上节点的代码
这里爬的就是百度百科里面“网络爬虫”和相关的词条及它们简介
这是词条名称的节点

网络爬虫

...

这是词条url的节点

万维网

这是词条简介的节点

网络爬虫(又称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫

3. 编码阶段

spider_main.py

# coding:utf8
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 == 1000:
                    break
                
                count = count + 1
            except:
                print ('craw failed')
                
            
        self.outputer.output_html()

if __name__=="__main__":
    root_url = "https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB"
    obj_spider = SpiderMain()
    obj_spider.craw(root_url)

url_manager.py

# 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

html_downloader.py

# coding:utf8
import urllib.request

class HtmlDownloader(object):


    def download(self, url):
        if url is None:
            return None
        
        response = urllib.request.urlopen(url)

        if response.getcode() != 200:
            return None
        

        return response.read().decode('utf-8')

html_parser.py

# coding:utf8
from bs4 import BeautifulSoup
import re
from urllib import parse

class HtmlParser(object):


    def _get_new_urls(self, page_url, soup):
        new_urls = set()
        #  https://baike.baidu.com/item/%E5%91%A8%E5%86%AC%E9%9B%A8
        links = soup.find_all('a', href=re.compile(r"/item/.*"))
        for link in links:
            new_url = link['href']
            new_full_url = parse.urljoin(page_url, new_url)
            new_urls.add(new_full_url)
        return new_urls

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

        res_data['url'] = page_url
        
        # 

周冬雨

title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find("h1") res_data['title'] = title_node.get_text() #
summary_node = soup.find('div', class_="lemma-summary") res_data['summary'] = summary_node.get_text() return res_data def parse(self, page_url, html_cont): if page_url is None or html_cont is None: return soup = BeautifulSoup(html_cont, 'html.parser') new_urls = self._get_new_urls(page_url, soup) new_data = self._get_new_data(page_url, soup) return new_urls, new_data

html_outputer.py

# 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("")
        fout.write("")
        fout.write("")
        fout.write("")
        fout.write("")
        fout.write("")

        # ascii
        for data in self.datas:
            fout.write("")
            # fout.write("" % data['url'].encode('utf-8').decode('utf-8'))
            fout.write("" % data['title'].encode('utf-8').decode('utf-8'))
            fout.write("" % data['summary'].encode('utf-8').decode('utf-8'))
            fout.write("")


        fout.write("
%s%s%s
") fout.write("") fout.write("") fout.close()

4. 测试阶段

运行spider_main.py,结果如下:

======== RESTART: C:\Users\0.0\Desktop\python\spider_百度百科\spider_main.py =======
craw 1 : https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB
craw 2 : https://baike.baidu.com/item/YaCy
craw 3 : https://baike.baidu.com/item/%E6%90%9C%E7%B4%A2%E7%AD%96%E7%95%A5
craw 4 : https://baike.baidu.com/item/%E6%96%AF%E5%9D%A6%E7%A6%8F
craw 5 : https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E6%9C%8D%E5%8A%A1%E5%99%A8
craw 6 : https://baike.baidu.com/item/%E5%B7%9E%E9%95%BF
craw 7 : https://baike.baidu.com/item/PageRank
craw 8 : https://baike.baidu.com/item/%E5%86%97%E4%BD%99%E6%8A%80%E6%9C%AF
craw 9 : https://baike.baidu.com/item/%E6%97%A5%E5%BF%97/2769135
craw 10 : https://baike.baidu.com/item/%E7%AE%97%E6%B3%95
...

再打开当前文件夹下的output.html
记一个爬虫实例_第1张图片
成功!!!

你可能感兴趣的:(其他)