python3 爬虫五大模块之五:信息采集器

Python的爬虫框架主要可以分为以下五个部分:

爬虫调度器:用于各个模块之间的通信,可以理解为爬虫的入口与核心(main函数),爬虫的执行策略在此模块进行定义;

URL管理器:负责URL的管理,包括带爬取和已爬取的URL、已经提供相应的接口函数(类似增删改查的函数)

网页下载器:负责通过URL将网页进行下载,主要是进行相应的伪装处理模拟浏览器访问、下载网页

网页解析器:负责网页信息的解析,这里是解析方式视具体需求来确定

信息采集器:负责将解析后的信息进行存储、显示等处理


代码示例是爬取CSDN博主下的所有文章为例,文章仅作为笔记使用,理论知识rarely

一、信息采集器简介

       信息采集器的功能基本是将解析后的信息进行显示、存储到本地磁盘上。   

       信息采集器也许名字并不正确,自己突发奇想来的。我对解析器和采集器的区分不是很明确,在下面的示例中可能在采集器中依然进行了网页解析,主要原因在于对python的基本语法不熟,有些数据统一处理还不会,只能边解析边存储了。

二、信息采集器示例:(爬取CSDN博主下的所有文章

# author : s260389826
# date : 2019/3/22
# position: chengdu


from fake_useragent import UserAgent
import urllib.request as request
from bs4 import BeautifulSoup
import urllib.parse
import os
import tomd


class HtmlOutputer(object):

    # Replace deny char, used to name a directory.
    def replace_deny_char(self, title):
        deny_char = ['\\', '/', ':', '*', '?', '\"', '<', '>', '|', ':']
        for char in deny_char:
            title = title.replace(char, ' ')
        print('Article\'title is: %s' % title)
        return title

    def img_download(self, img_url, directory, n):
        opener = urllib.request.build_opener()
        opener.addheaders = [('User-agent', str(UserAgent().random))]
        urllib.request.install_opener(opener)
        try:
            img_name = '%s\%s.jpg' % (directory, n)
            if os.path.exists(img_name) is True:
                return
            request.urlretrieve(img_url, img_name)
            print('图片%d下载操作完成' % n)
        except Exception as e:
            print(e)

    def collect(self, author, seq, html):

        soup = BeautifulSoup(html,'html.parser', from_encoding='utf-8')


        try:
            # <h1 class="title-article">Windos下通过Wpcap抓包实现两个网卡桥接</h1>
            article_title = soup.find('h1',attrs={'class': "title-article"}).text  # 获取文章标题 print(soup.h1.text)

            # <span class="time">2018年12月18日 16:43:02</span>
            # article_time = soup.find('span',attrs={'class': "time"}).text  # 获取文章时间
            # assert isinstance(article_time, object)

            # <span class="read-count">阅读数:104</span>
            # article_readcnt= soup.find('span', attrs={'class': "read-count"}).text  # 获取文章阅读量
            # print(article_title, article_time, article_readcnt)

        except AttributeError as e:
            #print(e.reason)
            return

        article_title_convert = self.replace_deny_char(article_title)
        directory = "F:\python\CSDN\\blog\%s\%d.%s" % (author, seq, article_title_convert)
        if os.path.exists(directory) is False:
            os.makedirs(directory)

        # download blog'imgs:
        # <div id="article_content">
        imgs = soup.find('div', attrs={'id' : "article_content"}).findAll('img')

        if len(imgs) > 0:
            count = 0
            for img in imgs:
                count = count + 1
                # print(img.attrs['src'])
                self.img_download(img.attrs['src'], directory, count)

        # down blog's ariticles:  如果要保存文件,需要将注释打开
        '''
        article = soup.find('div', attrs={'id' : "article_content"})
        md = tomd.convert(article.prettify())
        try:
            with open('%s\%s.md' % (directory, article_title_convert), 'w', encoding='utf-8') as f:
                f.write(md)
        except FileNotFoundError as e:
            print("No such file or directory: %s\%s" % (directory, article_title_convert))
        '''

三、上述代码用到的知识点:

       1. 对系统目录及文件的处理:

directory = "F:\python\CSDN\\blog\s2603898260"
if os.path.exists(directory) is False:   # 如果该目录不存在
    os.makedirs(directory)               # 则进行创建目录

file_name = "F:\python\CSDN\\blog\s2603898260\log.txt"
if os.path.exists(file_name) is True:    # 如果该文件存在
    return                               # 不需要重新下载,直接返回

       2. 特殊字符不能做文件名处理:

    # Replace deny char, used to name a directory.
    def replace_deny_char(self, title):
        deny_char = ['\\', '/', ':', '*', '?', '\"', '<', '>', '|', ':']
        for char in deny_char:
            title = title.replace(char, ' ')
        print('Article\'title is: %s' % title)
        return title

     3. 根据URL下载图片:

    request.urlretrieve(img_url, img_name)  # 根据img_url 下载图片到本地img_name(完整目录+图片名.格式)

   def img_download(self, img_url, directory, n):
        opener = urllib.request.build_opener()
        opener.addheaders = [('User-agent', str(UserAgent().random))]
        urllib.request.install_opener(opener)
        try:
            img_name = '%s\%s.jpg' % (directory, n)
            if os.path.exists(img_name) is True:
                return
            request.urlretrieve(img_url, img_name)
            print('图片%d下载操作完成' % n)
        except Exception as e:
            print(e)

     4. tomd插件:

        作用就是将html格式转换为td的格式。没理解错就是它:

                                                          

       不是很懂,我的下载转换效果也不是很好,

      直接附链接:https://github.com/gaojiuli/tom

      以及阅读td文件的链接:http://markdownpad.com/download.html

 

 

 

 

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叨陪鲤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值