Scrapy 框架 安装 五大核心组件 settings 配置 管道存储

scrapy 框架的使用

博客: https://www.cnblogs.com/bobo-zhang/p/10561617.html

安装:

  1. pip install wheel

  2. 下载 Twisted-18.9.0-cp36-cp36m-win_amd64.whl
    下载地址: https://www.lfd.uci.edu/~gohlke/pythonlibs/

  3. 安装 twisted

    pip install Twisted-18.9.0-cp36-cp36m-win_amd64.whl

  4. pip install pywin32

  5. pip install scrapy

基础使用:

  1. 创建项目:
    • scrapy startproject 项目名称
    • cd 到项目目录中
  2. 创建爬虫文件
    • scrapy genspider 文件名称 www.xxx.com
    • 课创建多个爬虫文件

Settings参数:

ROBOTSTXT_OBEY = True  #----------- 是否遵守robots.txt

CONCURRENT_REQUESTS = 16  ## ----------- 开启线程数量,默认16

AUTOTHROTTLE_START_DELAY = 3  # ----------- 开始下载时限速并延迟时间

AUTOTHROTTLE_MAX_DELAY = 60  # ----------- 高并发请求时最大延迟时间

# 最底下的几个:是否启用在本地缓存,如果开启会优先读取本地缓存,从而加快爬取速度,视情况而定

HTTPCACHE_ENABLED = True

HTTPCACHE_EXPIRATION_SECS = 0

HTTPCACHE_DIR = 'httpcache'

HTTPCACHE_IGNORE_HTTP_CODES = []

HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

# 以上几个可以视项目需要开启,但是有两个参数最好每次都开启,而每次都是项目文件手动开启不免有些麻烦,最好是项目创建后就自动开启

# DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',

# 这个是浏览器请求头,很多网站都会检查客户端的headers,比如豆瓣就是每一个请求都检查headers的user_agent,否则只会返回403,可以开启

#USER_AGENT = 'Chirco (+http://www.yourdomain.com)'

# 这个是至关重要的,大部分服务器在请求快了会首先检查User_Agent,而scrapy默认的浏览器头是scrapy1.1 我们需要开启并且修改成浏览器头,如:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1

# 解开注释 
ITEM_PIPELINES = {
    #  300 表示权重 越小优先级越高
    'DemoPro.pipelines.DemoproPipeline': 300,
}
# 只打印 错误信息
LOG_LEVEL = 'ERROR'
LOG_FILE = 'log.txt'

五大核心组件:

  1. 引擎 ** (Scrapy)
    用来处理整个系统的数据流处理(分发),
    *触发事务
    (框架核心*)*
  2. 调度器 (Scheduler)
    用来接受引擎发过来的请求,压入队列中,并在引擎再次请求的时候返回.可以想像成一个URL抓取网页的网址或者说是链接的优先队列,* *由它来决定下一个要抓取的网址是什么,* 同时去除重复的网址
  3. 下载器 (Downloader)
    用于下载网页内容,* 并将网页内容返回给蜘蛛(Scrapy)下载器是建立在twisted这个高效的异步模型上的)
  4. 爬虫 ** (Spiders)
    爬虫是主要干活的,
    用于从特定的网页中提取自己需要的信息,即所谓的实体(Item)用户也可以从中提取出链接,让* *Scrapy继续抓取下一个页面**, 产生url 解析数据
  5. 管道 ** (Pipeline)
    负责处理爬虫从网页中抽取的实体
    主要的功能是持久化实体验证实体的有效性清除不需要的信息当页面被爬虫解析后将被发送到项目管道并经过几个特定的次序处理数据**。

请求流程:

spider -> 引擎 -> 调度器(去重,调度器) -> 引擎 -> 下载器 -> 网络 -> 下载器 -> 引擎 -> spider ->管道

爬虫文件:

class DemoSpider(scrapy.Spider):
    name = 'demo'  # 爬蟲文件的名称 
    # 允许的域名
    # allowed_domains = ['www.xxx.com']
	# 起始的 url 列表
    start_urls = ['https://www.qiushibaike.com/text/']
    # 请求成功的 回调函数  实现数据解析
    def parse(self, response):
        response.body # 获取二进制数据  同  requests 中的 content
        response.text  # 获取响应的 数据
        response.xpath()  # 直接使用 xpath 函数  
        # 只能取出一个 元素
        author = div.xpath('./div/a[2]/h2/text()').extract_first()
        # 返回的列表元素时一个 selector 对象  
        content = div.xpath('./a[1]//text()').extract()
基于终端指令的的 存储   scrapy crawl demo -o qiubai.csv 

基于管道的永久存储

  1. 进行数据解析(author content)
  2. 在item类中定义相关的属性
  3. 在parse方法中实例化一个item类型的对象
  4. 将解析到的数据存储到item类型的对象中
  5. 使用yiled item将item对象提交给管道
  6. 在管道文件的process_item方法中接收item且对item中存储数据进行持久化存储
  7. 在settings配置文件中开启管道
  • settings 配置

    USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
    
    # Obey robots.txt rules
    ROBOTSTXT_OBEY = False
    
    # 解开注释 
    ITEM_PIPELINES = {
        #  300 表示权重 越小优先级越高
        'DemoPro.pipelines.DemoproPipeline': 300,
    }
    # 只打印 错误信息
    LOG_LEVEL = 'ERROR'
    
  • 在items.py 文件中

    class DemoproItem(scrapy.Item):
        # define the fields for your item here like:
        # name = scrapy.Field()
        # 对应要存储的 元素
        author = scrapy.Field()
        content = scrapy.Field()
        pass
    
  • 实现 爬虫文件中

    import scrapy
    from DemoPro.items import DemoproItem
    
    class DemoSpider(scrapy.Spider):
        
    	def parse(self, response):
            div_list = response.xpath('//div[@id="content-left"]/div')
    
            for div in div_list:
                author = div.xpath('./div/a[2]/h2/text()').extract_first()
                content = div.xpath('./a[1]/div/span[1]//text()').extract()
                content = '  '.join([i.strip() for i in content])
                print(author, content)
                item = DemoproItem()
                # 并且将解析到的数据封装存储到了item类型的对象当中了
                item['author'] = author
                item['content'] = content
    
                # 向管道提交item类型的对象
                yield item
    
    

    在管道文件中进行 存储

    • pipeline.py
    class DemoproPipeline(object):
        fp = None
    
        # 这个方法只执行一次
        def open_spider(self, spider):
            """ 父类的方法 开启文件句柄 """
            self.fp = open('qiubai.txt', 'w', encoding='utf-8')
    
        def process_item(self, item, spider):
            author = item['author']
            content = item['content']
            self.fp.write(author + '\n' + content + '\n')
            return item  # 返回给了下一个即将被执行的管道类
    
        def close_spider(self, spider):
            self.fp.close()
    

使用mysql 存储

settings 配置

ITEM_PIPELINES = {
    'DemoPro.pipelines.DemoproPipeline': 300,
    'DemoPro.pipelines.MySqlPipeline': 301,
    'DemoPro.pipelines.RedisPipeline': 302,
    # ... 注册其他的管道 类  300 为权重  权重小的 先执行
    # 可注册使用 mysql redis mongodb .. 数据库
}
class MySqlPipeline(object):
    conn = None
    cursor = None

    def open_spider(self, spider):
        self.conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='', db='spider')

    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute('insert into data(author, content) values(%s,%s)' % (item["author"], item["content"]))
            self.conn.commit()
            print(item['author'])

        except Exception as e:
            print(e, 11111111)
            self.conn.rollback()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()

使用redis 存储



class RedisPipeline(object):
    conn = None

    def open(self, spider):
        self.conn = redis.Redis(host='127.0.0.1', port=6379)

    def process_item(self, item, spider):
        data = {
            'author': item['author'],
            'content': item['content']
        }
        self.conn.lpush('qiubaiData', data)

posted @ 2019-04-22 12:19  拐弯  阅读(500)  评论(0编辑  收藏  举报