爬虫:scrapy架构介绍、scrapy解析数据、settings相关配置,提高爬取效率、持久化方案、全站爬取cnblogs文章

发布时间 2023-06-27 10:14:16作者: wwwxxx123

scrapy架构介绍

image

# 引擎(EGINE)
引擎负责控制系统所有组件之间的数据流,并在某些动作发生时触发事件。

# 调度器(SCHEDULER)
用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL的优先级队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址

# 下载器(DOWLOADER)
用于下载网页内容, 并将网页内容返回给EGINE,下载器是建立在twisted这个高效的异步模型上的

# 爬虫(SPIDERS)--->在这里写代码
SPIDERS是开发人员自定义的类,用来解析responses,并且提取items,或者发送新的请求

# 项目管道(ITEM PIPLINES)
在items被提取后负责处理它们,主要包括清理、验证、持久化(比如存到数据库)等操作

# 下载器中间件(Downloader Middlewares)

位于Scrapy引擎和下载器之间,主要用来处理从EGINE传到DOWLOADER的请求request,已经从DOWNLOADER传到EGINE的响应response,你可用该中间件做以下几件事:设置请求头,设置cookie,使用代理,集成selenium

# 爬虫中间件(Spider Middlewares)
位于EGINE和SPIDERS之间,主要工作是处理SPIDERS的输入(即responses)和输出(即requests)

scrapy的一些命令

安装完成后  会有scrapy的可执行文件

# 创建项目
   scrapy startproject 项目名字  # 跟创建dajngo一样,pycharm能直接创建django
   
# 创建爬虫
   scrapy genspider 名字 域名  # 创建爬虫类似django的创建app
   
   eg:scrapy genspider baidu www.baidu.com

# pycharm打开scrapy的项目

运行爬虫
   scrapy crawl 爬虫名字
   
想点击绿色箭头运行爬虫
   新建一个run.py,写入,以后右键执行即可
   from scrapy.cmdline import execute
   execute(['scrapy','crawl','cnblogs','--nolog'])
   

补充:爬虫协议
    http://www.cnblogs.com/robots.txt

scrapy项目目录结构

firstscrapy          #  项目名
     firstscrapy     #  文件夹名字,核心代码,都在这里面
          spiders    # 爬虫的文件,里面有所有的爬虫
               __init__.py 
               baidu.py   # 百度爬虫
               cnblogs.py  # cnblogs爬虫
          items.py  # 有很多模型类---》以后存储的数据,都做成模型类的对象,等同于django的models.py
          middlewares.py  # 中间件:爬虫中间件,下载中间件都写在这里面
          pipelines.py   # 项目管道---》以后写持久化,都在这里面写
          run.py         # 自己写的,运行爬虫
          settings.py    # 配置文件 django的配置文件
      scrapy.py          # 项目上线用的,不需要关注

scrapy解析数据

1  response对象有css方法和xpath方法
    css 中写css选择器
    xpath中写xpath选择
2  重点1:
    xpath取文本内容
    './/a[contains(@class,"link-title")]/text()'
    xpath取属性
     './/a[contains(@class,"link-title")]/@href'
    css取文本
    'a.link-title::text'
    css取属性
    'img.image-scale::attr(src)'
3  重点2:
    .extract_first()    取一个
    .extract()          取所有

解析cnblogs

    # 解析返回的数据
    # 方式一   bs4  解析
    #     print(response.text)
    # soup = BeautifulSoup(response.text,'lxml')

    #  方式二:  自带的解析
    #     response.css()
    #     response.xpath()

    # def parse(self, response):
    #     # 解析数据  css解析
    #     article_list = response.css('article.post-item')
    #     for article in article_list:
    #         title = article.css('div.post-item-text>a::text').extract_first()
    #         author_img = article.css('div.post-item-text img::attr(src)').extract_first()
    #         author_name = article.css('footer span::text').extract_first()
    #         desc_old = article.css('p.post-item-summary::text').extract()
    #         desc = desc_old[0].replace('\n', '').replace(' ', '')
    #         if not desc:
    #             desc = desc_old[1].replace('\n', '').replace(' ', '')
    #             url = article.css('div.post-item-text>a::attr(href)').extract_first()
    #         #     # 文章真正的内容,没拿到,它不在这个页面中,它在下一个页面中
    #         print(title)
    #         print(author_img)
    #         print(author_name)
    #         print(desc)
    #         print(url)
    def parse(self, response):
        # 解析数据  xpath解析
        article_list = response.xpath('//*[@id="post_list"]/article')
        # article_list = response.xpath('//article[contains(@class,"post-item")]')
        for article in article_list:
            title = article.xpath('.//div/a/text()').extract_first()
            author_img = article.xpath('.//div//img/@src').extract_first()
            author_name = article.xpath('.//footer//span/text()').extract_first()
            desc_old = article.xpath('.//p/text()').extract()
            desc = desc_old[0].replace('\n', '').replace(' ', '')
            if not desc:
                desc = desc_old[1].replace('\n', '').replace(' ', '')
                url = article.xpath('.//div/a/@href').extract_first()
            # 文章真正的内容,没拿到,它不在这个页面中,它在下一个页面中
            print(title)
            print(author_img)
            print(author_name)
            print(desc)
            print(url)

settings相关配置,提高爬取效率

scrapy 项目有项目自己的配置文件,还有内置的

基础的一些

# 1 了解
BOT_NAME = "firstscrapy"  #项目名字,整个爬虫名字

# 2 爬虫存放位置  了解
SPIDER_MODULES = ["firstscrapy.spiders"]
NEWSPIDER_MODULE = "firstscrapy.spiders"

# 3 记住 是否遵循爬虫协议,一般都设为False
ROBOTSTXT_OBEY = False

# 4 记住
USER_AGENT = "firstscrapy (+http://www.yourdomain.com)"

# 5 记住 日志级别
LOG_LEVEL='ERROR'

# 6 记住 DEFAULT_REQUEST_HEADERS 默认请求头
DEFAULT_REQUEST_HEADERS = {
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
   'Accept-Language': 'en',
}

# 7 记住   SPIDER_MIDDLEWARES 爬虫中间件
SPIDER_MIDDLEWARES = {
    'cnblogs.middlewares.CnblogsSpiderMiddleware': 543,
}

# 8 记住 DOWNLOADER_MIDDLEWARES  下载中间件
DOWNLOADER_MIDDLEWARES = {
    'cnblogs.middlewares.CnblogsDownloaderMiddleware': 543,
}

# 9 记住 ITEM_PIPELINES 持久化配置 数值越小优先级越高
ITEM_PIPELINES = {
    'cnblogs.pipelines.CnblogsPipeline': 300,
}

增加爬虫的爬取效率

# 1 增加并发:默认16
默认scrapy开启的并发线程为32个 可以适当进行增加,在settings配置文件中修改
CONCURRENT_REQUESTS = 100   值为100,并发设置成了为100。

# 2 降低日志级别:
在运行scrapy时,会有大量日志信息的输出,为了减少CPU的使用率。可以设置log输出信息为INFO和ERROR即可。在配置文件中编写
LOG_LEVEL = 'INFO'

# 3 禁止cookie:
如果不是真的需要cookie,则在scrapy爬取数据时可以禁止cookie从而减少CPU的使用率,提升爬取效率。在配置文件中编写:
COOKIES_ENABLED = False

# 4 禁止重试:
对失败的HTTP进行重新请求(重试)会减慢爬取速度,因此可以禁止重试。在配置文件中编写:
RETRY_ENABLED = False

# 5 减少下载超时:
如果对一个非常慢的链接进行爬取,减少下载超时可以让卡住的链接快速被放弃,从而提升效率,在配置文件中进行编写:
DOWNLOAD_TIMEOUT = 10 超时时间为10s

持久化方案

方式一:(parse必须有return值,必须是列表套字典形式---》使用命令,可以报错到json格式中,csv中(后缀 excel打开是表格)。。。)

执行
scrapy crawl cnblogs -o cnbogs.json

方式二:我们用的,使用pipline存储--》可以存到多个位置
   第一步:在item.py中写一个类
      class FirstscrapyItem(scrapy.Item):
            title = scrapy.Field()
            author_img = scrapy.Field()
            author_name = scrapy.Field()
            desc = scrapy.Field()
            url = scrapy.Field()
            # 博客文章内容,但是暂时没有
            content = scrapy.Field()
   第二步:在pipline.py 中写代码,写一个类:
   class FirstscrapyFilePipeline:
    def open_spider(self, spider):
        print('我开了')
        self.f = open('a.txt', 'w', encoding='utf-8')

    def close_spider(self, spider):
        print('我关了')
        self.f.close()

    def process_item(self, item, spider):
        # item:是要报错的数据的对象
        # print(item['title'])
        # 把数据保存到文件中
        self.f.write(item['title'] + '\n')
        return item
   第三步:配置文件配置
       ITEM_PIPELINES = {
           "firstscrapy.pipelines.FirstscrapyFilePipeline": 300,  # 数字越小,优先级越高
        }
   第四步:在解析方法parse中yield item对象
   
以上是把爬取的数据插入到txt文件中
插入到数据库中 需要 mysqldb模块
1.提前建好数据库和表
在配置文件中添加以下字段 对应链接数据库
mysql_host='127.0.0.1'     #地址
mysql_user=''              #经过授权的用户名
mysql_passwd=''            #经过授权的访问密码
mysql_db=''                #数据库名称
mysql_tb=''                #表名
mysql_port=3306            #端口,默认3306


配置文件中添加往数据库添加数据的配置如:
ITEM_PIPELINES = {
        #数字越小优先级越高
        #menu.pipelines.Class,Class与pipelines.py里的类名对应,如:menu.pipelines.MenusqlPipeline
    'menu.pipelines.MenuPipeline': 300,   
    'menu.pipelines.MenusqlPipeline': 2,        #提交到数据库
}

在pipline.py中添加以下的代码 保证链接数据库 和添加数据(中间字段和前面写的不一样 修改一致即可)

import MySQLdb
from .settings import mysql_host,mysql_db,mysql_user,mysql_passwd,mysql_port
class MenusqlPipeline(object):
    def __init__(self):
        host=mysql_host
        user=mysql_user
        passwd=mysql_passwd
        port=mysql_port
        db=mysql_db
        self.connection=MySQLdb.connect(host,user,passwd,db,port,charset='utf8')
        self.cursor=self.connection.cursor()
    def process_item(self, item, spider):
        sql = "insert into cookbook2(name,step,sugar,energy,fat,material1,needtime,img,level,material2) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
         #注意 params添加的顺序要和sql语句插入的顺序一致,否则会出现错位甚至插入失败的情况
        params=list()
        params.append(item['name'])
        params.append(item['step'])
        params.append(item['sugar'])
        params.append(item['energy'])
        params.append(item['fat'])
        params.append(item['material1'])
        params.append(item['needtime'])
        params.append(item['material2'])
        params.append(item['img'])
        params.append(item['level'])
        self.cursor.execute(sql,tuple(params))
        self.connection.commit()
        return item
    def __del__(self):
        self.cursor.close()
        self.connection.close()

启动爬虫,查看数据库数据插入是否正常

https://blog.csdn.net/L_Shaker/article/details/118891300 该博客可以借鉴

全站爬取cnblogs文章

request和response对象传递参数 解析下一页并继续爬取

    def parse(self, response):
        # 解析数据  xpath解析
        article_list = response.xpath('//*[@id="post_list"]/article')
        # article_list = response.xpath('//article[contains(@class,"post-item")]')
        # l=[]
        for article in article_list:
            item = FirstscrapyItem()
            title = article.xpath('.//div/a/text()').extract_first()
            item['title'] = title
            author_img = article.xpath('.//div//img/@src').extract_first()
            item['author_img'] = author_img
            author_name = article.xpath('.//footer//span/text()').extract_first()
            item['author_name'] = author_name
            desc_old = article.xpath('.//p/text()').extract()
            desc = desc_old[0].replace('\n', '').replace(' ', '')
            if not desc:
                desc = desc_old[1].replace('\n', '').replace(' ', '')
            item['desc'] = desc
            url = article.xpath('.//div/a/@href').extract_first()
            item['url'] = url
            # yield item
            # print(title)
            yield Request(url=url, callback=self.parser_detail,meta={'item':item})  # 爬完后的执行的解析方法

        next = 'https://www.cnblogs.com' + response.css('div.pager>a:last-child::attr(href)').extract_first()
        print(next)  # 继续爬取
        yield Request(url=next, callback=self.parse)

    def parser_detail(self, response):
        # print(response.status)
        #  解析出文章内容
        content = response.css('#cnblogs_post_body').extract_first()
        # print(str(content))
        # 怎么放到item中
        item = response.meta.get('item')
        if content:
            item['content'] = content
        else:
            item['content'] = '没查到'
        yield item