Scrapy框架

Scrapy框架

  • 官网连接:点击
  • Scrapy一个开源和协做的框架,其最初是为了页面抓取 (更确切来讲, 网络抓取 )所设计的,使用它能够以快速、简单、可扩展的方式从网站中提取所需的数据。
  • 但目前Scrapy的用途十分普遍,可用于如数据挖掘、监测和自动化测试等领域,也能够应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。
  • Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架。所以Scrapy使用了一种非阻塞(又名异步)的代码来实现并发。

1、框架安装和基础使用

一、安装

  • linux mac os:
    1. pip install scrapy
  • win:
    1. pip install wheel
    2. 下载twisted:https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
    3. pip install 下载好的框架.whl
    4. pip install pywin32
    5. pip install scrapy

二、基础使用

  1. 建立一个工程:scrapy startproject工程名称
  2. 在工程目录下建立一个爬虫文件:
    1. cd 工程
    2. scrapy genspider 爬虫文件的名称 起始url (例如:scrapy genspider qiubai www.qiushibaike.com)
  3. 对应的文件中编写爬虫程序来完成爬虫的相关操做
  4. 设置修改settings.py配置文件相关配置:
    1. 19行:USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' #假装请求载体身份
    2. 22行:ROBOTSTXT_OBEY = False #能够忽略或者不遵照robots协议
  5. 执行爬虫程序:scrapy crawl 应用名称
    1. scrapy crawl 爬虫名称 :该种执行形式会显示执行的日志信息
    2. scrapy crawl 爬虫名称 --nolog:该种执行形式不会显示执行的日志信息
"""
目录结构:
project_name/
   scrapy.cfg:
   project_name/
       __init__.py
       items.py
       pipelines.py
       settings.py
       spiders/
           __init__.py

scrapy.cfg   项目的主配置信息。(真正爬虫相关的配置信息在settings.py文件中)
items.py     设置数据存储模板,用于结构化数据,如:Django的Model
pipelines    数据持久化处理
settings.py  配置文件,如:递归的层数、并发数,延迟下载等
spiders      爬虫目录,如:建立文件,编写爬虫解析规则
"""

#spiders/qiubai.py
import scrapy

class QiubaiSpider(scrapy.Spider):
    # 爬虫文件的名称:经过爬虫文件的名称能够指定的定位到某一个具体的爬虫文件
    name = 'qiubai'
    #容许的域名:只能够爬取指定域名下的页面数据(若是遇到非该域名的url则爬取不到数据)
    #通常不用直接注释了
    #allowed_domains = ['https://www.qiushibaike.com/']
    #起始url:当前工程将要爬取的页面所对应的url
    start_urls = ['https://www.qiushibaike.com/']

    # 解析方法:访问起始URL并获取结果后的回调函数
    # 该函数的response参数就是向起始的url发送请求后,获取的响应对象
    # parse方法的返回值必须为可迭代对象或者NUll
    def parse(self, response):
        print(response.text) #获取字符串类型的响应内容
        print(response.body)#获取字节类型的相应内容

        # 建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口)
        # xpath为response中的方法,能够将xpath表达式直接做用于该函数中
        odiv = response.xpath('//div[@id="content-left"]/div')
        content_list = []  # 用于存储解析到的数据
        for div in odiv:
            #xpath解析到的指定内容被存储到了Selector对象
            #extract()该方法能够将Selector对象中存储的数据值拿到
            #author = div.xpath('./div/a[2]/h2/text()').extract()[0]
            #extract_first()  ==   extract()[0]

            # xpath函数返回的为列表,列表中存放的数据为Selector类型的数据。
            # 咱们解析到的内容被封装在了Selector对象中,须要调用extract()函数将解析的内容从Selecor中取出。
            author = div.xpath('.//div[@class="author clearfix"]/a/h2/text()')[0].extract()
            content = div.xpath('.//div[@class="content"]/span/text()')[0].extract()

            # author = div.xpath('./div/a[2]/h2/text()').extract_first()
            # content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            # 将解析到的内容封装到字典中
            dic = {
                '做者': author,
                '内容': content
            }
            # 将数据存储到content_list这个列表中
            content_list.append(dic)

        return content_list


"""
settings.py
19行
22行
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False
基本使用

2、持久化存储

  • 磁盘文件:
    1. 基于终端指令:
      1. 保证parse方法返回一个可迭代类型的对象(存储解析到的页面内容)
      2. 使用终端指令完成数据存储到制定磁盘文件中的操做
      3. scrapy crawl 爬虫文件名称–o 磁盘文件.后缀
      4. scrapy crawl qiubai -o qiubai.csv --nolog
      5. scrapy crawl qiubai -o qiubai.json --nolog
      6. scrapy crawl qiubai -o qiubai.xml --nolog
    2. 基于管道:
      1. items:数据结构模板文件,定义数据属性,存储解析到的页面数据
      2. pipelines:管道文件,接收数据(items),处理持久化存储的相关操做
      3. 代码实现流程:
        1. 爬虫文件爬取到数据后,须要将数据存储到items对象中。
        2. 使用yield关键字将items对象提交给pipelines管道文件进行持久化处理
        3. 在管道文件中的process_item方法中接收爬虫文件提交过来的item对象,而后编写持久化存储的代码将item对象中存储的数据进行持久化存储
        4. settings.py配置文件中开启管道
  • 数据库:
    1. mysql
    2. redis
    3. 编码流程:
      1. 将解析到的页面数据存储到items对象
      2. 使用yield关键字将items提交给管道文件进行处理
      3. *****在管道文件中编写代码完成数据存储的操做【】
      4. 在配置文件中开启管道操做
"""
基于终端指令
1.保证parse方法返回一个可迭代类型的对象(存储解析到的页面内容)
2.使用终端指令完成数据存储到制定磁盘文件中的操做
scrapy crawl qiubai -o qiubai.csv --nolog
"""
# -*- coding: utf-8 -*-
import scrapy
class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.qiushibaike.com/text']
    start_urls = ['https://www.qiushibaike.com/text/']
    def parse(self, response):
        #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口)
        # 段子的内容和做者
        div_list = response.xpath('//div[@id="content-left"]/div')
        #存储解析到的页面数据
        data_list = []
        for div in div_list:
            #xpath解析到的指定内容被存储到了Selector对象
            #extract()该方法能够将Selector对象中存储的数据值拿到
            #author = div.xpath('./div/a[2]/h2/text()').extract()[0]
            #extract_first()  ==   extract()[0]
            author = div.xpath('./div/a[2]/h2/text()').extract_first()
            content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            dict = {
                'author':author,
                'content':content
            }
            data_list.append(dict)
        return data_list


"""
settings.py
19行

22行
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
基于终端指令
"""
基于管道
1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py)
2.使用终端指令完成数据存储到制定磁盘文件中的操做
scrapy crawl qiubai --nolog
"""
# -*- coding: utf-8 -*-
import scrapy
from qiubaiPro.items import QiubaiproItem


class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    # allowed_domains = ['www.qiushibaike.com/text']
    start_urls = ['https://www.qiushibaike.com/text/']

    def parse(self, response):
        # 建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口)
        # 段子的内容和做者
        div_list = response.xpath('//div[@id="content-left"]/div')
        for div in div_list:
            # xpath解析到的指定内容被存储到了Selector对象
            # extract()该方法能够将Selector对象中存储的数据值拿到
            # author = div.xpath('./div/a[2]/h2/text()').extract()[0]
            # extract_first()  ==   extract()[0]
            author = div.xpath('./div/a[2]/h2/text()').extract_first()
            content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            # 1.将解析到的数据值(author和content)存储到items对象
            item = QiubaiproItem()
            item['author'] = author
            item['content'] = content

            # 2.将item对象提交给管道
            yield item


"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class QiubaiproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()


"""
pipelines.py
"""


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class QiubaiproPipeline(object):

    fp = None

    # # 构造方法
    # def __init__(self):
    #     self.fp = None  # 定义一个文件描述符属性

    # 整个爬虫过程当中,该方法只会在开始爬虫的时候被调用一次
    def open_spider(self, spider):
        print('开始爬虫')
        self.fp = open('./qiubai_pipe.txt', 'w', encoding='utf-8')

    # 该方法就能够接受爬虫文件中提交过来的item对象,而且对item对象中存储的页面数据进行持久化存储
    # 参数:item表示的就是接收到的item对象

    # 每当爬虫文件向管道提交一次item,则该方法就会被执行一次
    # 由于该方法会被执行调用屡次,因此文件的开启和关闭操做写在了另外两个只会各自执行一次的方法中。
    def process_item(self, item, spider):
        # print('process_item 被调用!!!')
        # 取出item对象中存储的数据值
        author = item['author']
        content = item['content']

        # 持久化存储
        self.fp.write(author + ":" + content + '\n\n\n')
        return item

    # 该方法只会在爬虫结束的时候被调用一次
    def close_spider(self, spider):
        print('爬虫结束')
        self.fp.close()


"""
settings.py
19行
22行
68行 开启管道
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
    'qiubaiPro.pipelines.QiubaiproPipeline': 300,  # 300表示为优先级,值越小优先级越高

}
基于管道
"""
基于mysql的管道存储
1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py)
2.使用终端指令完成数据存储到制定磁盘文件中的操做
scrapy crawl qiubai --nolog
"""
# -*- coding: utf-8 -*-
import scrapy
from qiubaiPro.items import QiubaiproItem

class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.qiushibaike.com/text']
    start_urls = ['https://www.qiushibaike.com/text/']
    def parse(self, response):
        #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口)
        # 段子的内容和做者
        div_list = response.xpath('//div[@id="content-left"]/div')
        for div in div_list:
            #xpath解析到的指定内容被存储到了Selector对象
            #extract()该方法能够将Selector对象中存储的数据值拿到
            #author = div.xpath('./div/a[2]/h2/text()').extract()[0]
            #extract_first()  ==   extract()[0]
            author = div.xpath('./div/a[2]/h2/text()').extract_first()
            content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            #1.将解析到的数据值(author和content)存储到items对象
            #建立items对象
            item = QiubaiproItem()
            item['author'] = author
            item['content'] = content

            #2.将item对象提交给管道
            yield item


"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class QiubaiproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()

"""
pipelines.py
"""
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
class QiubaiproPipelineByMysql(object):

    conn = None
    cursor = None
    def open_spider(self,spider):
        print('开始爬虫')
        #连接数据库
        self.conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='123456',db='qiubai')
    #编写向数据库中存储数据的相关代码
    def process_item(self, item, spider):
        #1.连接数据库
        #2.执行sql语句
        sql = 'insert into qiubai values("%s","%s")'%(item['author'],item['content'])
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
        #3.提交事务

        return item
    def close_spider(self,spider):
        print('爬虫结束')
        self.cursor.close()
        self.conn.close()

"""
settings.py
19行
22行
68行 开启管道
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
    'qiubaiPro.pipelines.QiubaiproPipelineByMysql': 300,  #300表示为优先级,值越小优先级越高
}
基于mysql的管道存储
"""
基于redis的管道存储
1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py)
2.使用终端指令完成数据存储到制定磁盘文件中的操做
scrapy crawl qiubai --nolog
"""
# -*- coding: utf-8 -*-
import scrapy
from qiubaiPro.items import QiubaiproItem

class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.qiushibaike.com/text']
    start_urls = ['https://www.qiushibaike.com/text/']
    def parse(self, response):
        #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口)
        # 段子的内容和做者
        div_list = response.xpath('//div[@id="content-left"]/div')
        for div in div_list:
            #xpath解析到的指定内容被存储到了Selector对象
            #extract()该方法能够将Selector对象中存储的数据值拿到
            #author = div.xpath('./div/a[2]/h2/text()').extract()[0]
            #extract_first()  ==   extract()[0]
            author = div.xpath('./div/a[2]/h2/text()').extract_first()
            content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            #1.将解析到的数据值(author和content)存储到items对象
            #建立items对象
            item = QiubaiproItem()
            item['author'] = author
            item['content'] = content

            #2.将item对象提交给管道
            yield item


"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class QiubaiproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()

"""
pipelines.py
"""
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import redis

class QiubaiproPipelineByRedis(object):
    conn = None
    def open_spider(self,spider):
        print('开始爬虫')
        self.conn = redis.Redis(host='127.0.0.1',port=6379)
    def process_item(self, item, spider):
        dict = {
            'author':item['author'],
            'content':item['content']
        }
        # 写入redis中
        self.conn.lpush('data', dict)
        return item

"""
settings.py
19行
22行
68行 开启管道
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
    'qiubaiPro.pipelines.QiubaiproPipelineByRedis': 300,  #300表示为优先级,值越小优先级越高
}
基于redis的管道存储
"""
不一样形式的持久化操做
1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py)
2.使用终端指令完成数据存储到制定磁盘文件中的操做
scrapy crawl qiubai --nolog
3.主要就是管道文件pipelines.py和配置文件settings.py
	-须要在管道文件中编写对应平台的管道类
	-在配置文件中对自定义的管道类进行生效操做
"""
# -*- coding: utf-8 -*-
import scrapy
from qiubaiPro.items import QiubaiproItem

class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.qiushibaike.com/text']
    start_urls = ['https://www.qiushibaike.com/text/']
    def parse(self, response):
        #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口)
        # 段子的内容和做者
        div_list = response.xpath('//div[@id="content-left"]/div')
        for div in div_list:
            #xpath解析到的指定内容被存储到了Selector对象
            #extract()该方法能够将Selector对象中存储的数据值拿到
            #author = div.xpath('./div/a[2]/h2/text()').extract()[0]
            #extract_first()  ==   extract()[0]
            author = div.xpath('./div/a[2]/h2/text()').extract_first()
            content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            #1.将解析到的数据值(author和content)存储到items对象
            #建立items对象
            item = QiubaiproItem()
            item['author'] = author
            item['content'] = content

            #2.将item对象提交给管道
            yield item


"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class QiubaiproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()

"""
pipelines.py
"""
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import redis

class QiubaiproByRedis(object):
    conn = None
    def open_spider(self,spider):
        print('开始爬虫')
        self.conn = redis.Redis(host='127.0.0.1',port=6379)
    def process_item(self, item, spider):
        dict = {
            'author':item['author'],
            'content':item['content']
        }
        # 写入redis中
        self.conn.lpush('data', dict)
        return item


class QiubaiproPipeline(object):
    fp = None
    # 整个爬虫过程当中,该方法只会在开始爬虫的时候被调用一次
    def open_spider(self, spider):
        print('开始爬虫')
        self.fp = open('./qiubai_pipe.txt', 'w', encoding='utf-8')

    # 该方法就能够接受爬虫文件中提交过来的item对象,而且对item对象中存储的页面数据进行持久化存储
    # 参数:item表示的就是接收到的item对象

    # 每当爬虫文件向管道提交一次item,则该方法就会被执行一次
    # 由于该方法会被执行调用屡次,因此文件的开启和关闭操做写在了另外两个只会各自执行一次的方法中。
    def process_item(self, item, spider):
        # print('process_item 被调用!!!')
        # 取出item对象中存储的数据值
        author = item['author']
        content = item['content']

        # 持久化存储
        self.fp.write(author + ":" + content + '\n\n\n')
        return item

    # 该方法只会在爬虫结束的时候被调用一次
    def close_spider(self, spider):
        print('爬虫结束')
        self.fp.close()

"""
settings.py
19行
22行
68行 开启管道
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

#下列结构为字典,字典中的键值表示的是即将被启用执行的管道文件和其执行的优先级。
ITEM_PIPELINES = {
    'qiubaiPro.pipelines.QiubaiproByRedis': 300,  #300表示为优先级,值越小优先级越高
    'qiubaiPro.pipelines.QiubaiproPipeline': 200,
}
#上述代码中,字典中的两组键值分别表示会执行管道文件中对应的两个管道类中的process_item方法,实现两种不一样形式的持久化操做。
不一样形式的持久化操做
"""
多个url页面数据爬取
1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py)
2.使用终端指令完成数据存储到制定磁盘文件中的操做
scrapy crawl qiubai --nolog
"""
# -*- coding: utf-8 -*-
import scrapy
from qiubaiByPages.items import QiubaibypagesItem

class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.qiushibaike.com/text']
    start_urls = ['https://www.qiushibaike.com/text/']

    #设计一个通用的url模板
    url = 'https://www.qiushibaike.com/text/page/%d/'
    pageNum = 1

    def parse(self, response):
        div_list = response.xpath('//*[@id="content-left"]/div')

        for div in div_list:
            author = div.xpath('./div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
            content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            #建立一个items对象,将解析到数据值存储到items对象中
            item = QiubaibypagesItem()
            item['author'] = author
            item['content'] = content

            #将item提交给管道
            yield item

        #请求的手动发送
        #13表示的是最后一页的页码
        if self.pageNum <= 13:
            print('爬取到了第%d页的页面数据'%self.pageNum)
            self.pageNum += 1
            new_url = format(self.url % self.pageNum)
            #callback:将请求获取到的页面数据进行解析
            yield scrapy.Request(url=new_url,callback=self.parse)


"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class QiubaibypagesItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()

"""
pipelines.py
"""
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class QiubaibypagesPipeline(object):
    fp = None
    def open_spider(self,spider):
        print('开始爬虫')
        self.fp = open('./qiubai.txt','w',encoding='utf-8')
    def process_item(self, item, spider):
        self.fp.write(item['author']+":"+item['content'])
        return item
    def close_spider(self,spider):
        self.fp.close()
        print('爬虫结束')

"""
settings.py
19行
22行
68行 开启管道
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
    'qiubaiByPages.pipelines.QiubaibypagesPipeline': 300,
}
多个url页面数据爬取

一、Scrapy核心组件

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

3、代理和cookie

一、post请求发送

  • 问题:在以前代码中,咱们历来没有手动的对start_urls列表中存储的起始url进行过请求的发送,可是起始url的确是进行了请求的发送,那这是如何实现的呢?
  • 解答:实际上是由于爬虫文件中的爬虫类继承到了Spider父类中的start_requests(self)这个方法,该方法就能够对start_urls列表中的url发起请求
  • 【注意】start_requests方法默认的实现,是对起始的url发起get请求,若是想发起post请求,则须要子类重写该方法。
"""
post请求发送
"""
# -*- coding: utf-8 -*-
import scrapy
#需求:百度翻译中指定词条对应的翻译结果进行获取
class PostdemoSpider(scrapy.Spider):
    name = 'postDemo'
    #allowed_domains = ['www.baidu.com']
    start_urls = ['https://fanyi.baidu.com/sug']
    #该方法实际上是父类中的一个方法:该方法能够对star_urls列表中的元素进行get请求的发送
    #发起post:
        #1.将Request方法中method参数赋值成post
        #2.FormRequest()能够发起post请求(推荐)
    def start_requests(self):
        print('start_requests()')
        #post请求的参数
        data = {
            'kw': 'dog',
        }
        for url in self.start_urls:
            #formdata:请求参数对应的字典
            yield scrapy.FormRequest(url=url,formdata=data,callback=self.parse)

    #发起get:
    # def start_requests(self):
    #     for u in self.start_urls:
    #         yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        print(response.text)
post请求发送

二、cookie

  • 登陆后,获取该用户我的主页这个二级页面的页面数据
"""
cookie:豆瓣网我的登陆,获取该用户我的主页这个二级页面的页面数据。
"""
# -*- coding: utf-8 -*-
import scrapy


class DoubanSpider(scrapy.Spider):
    name = 'douban'
    #allowed_domains = ['www.douban.com']
    start_urls = ['https://www.douban.com/accounts/login']

    #重写start_requests方法
    def start_requests(self):
        #将请求参数封装到字典
        data = {
            'source': 'index_nav',
            'form_email': '15027900535',
            'form_password': 'bobo@15027900535'
        }
        for url in self.start_urls:
            yield scrapy.FormRequest(url=url,formdata=data,callback=self.parse)
    #针对我的主页页面数据进行解析操做
    def parseBySecondPage(self,response):
        fp = open('second.html', 'w', encoding='utf-8')
        fp.write(response.text)

        #能够对当前用户的我的主页页面数据进行指定解析操做

    def parse(self, response):
        #登陆成功后的页面数据进行存储
        fp = open('main.html','w',encoding='utf-8')
        fp.write(response.text)

        #获取当前用户的我的主页
        url = 'https://www.douban.com/people/185687620/'
        yield scrapy.Request(url=url,callback=self.parseBySecondPage)
cookie

三、代理

  • 下载中间件做用:拦截请求,能够将请求的ip进行更换
  • 流程:下载中间件类的自制定
  • 配置文件中进行下载中间件的开启
"""
代理:
下载中间件做用:拦截请求,能够将请求的ip进行更换。
流程:
1.    下载中间件类的自制定
    a)    object
    b)    重写process_request(self,request,spider)的方法
2.    配置文件中进行下载中间件的开启。
"""
# -*- coding: utf-8 -*-
import scrapy

class ProxydemoSpider(scrapy.Spider):
    name = 'proxyDemo'
    #allowed_domains = ['www.baidu.com/s?wd=ip']
    start_urls = ['https://www.baidu.com/s?wd=ip']

    def parse(self, response):
        fp = open('proxy.html','w',encoding='utf-8')
        fp.write(response.text)


"""
middlewares.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

#自定义一个下载中间件的类,在类中事先process_request(处理中间价拦截到的请求)方法
class MyProxy(object):
    def process_request(self,request,spider):
        #请求ip的更换
        request.meta['proxy'] = "https://178.128.90.1:8080"

"""
settings.py
19行
22行
56行 开启下载中间件
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

DOWNLOADER_MIDDLEWARES = {
    'proxyPro.middlewares.MyProxy': 543,
}
代理

4、日志等级和请求传参

一、日志信息

  • 日志等级(种类):
    1. ERROR:错误
    2. WARNING:警告
    3. INFO:通常信息
    4. DEBUG:调试信息(默认)
  • 指定输入某一种日志信息:
    1. settings.py文件中配置:LOG_LEVEL ='ERROR'
  • 将日志信息存储到指定文件中,而并不是显示在终端里:
    1. settings.py文件中配置:LOG_FILE ='log.txt'

二、请求传参

  • 爬取的数据值不在同一个页面中。
  • 列表页和详情页的爬取
"""
请求传参
"""
# -*- coding: utf-8 -*-
import scrapy
from moviePro.items import MovieproItem

class MovieSpider(scrapy.Spider):
    name = 'movie'
    #allowed_domains = ['www.id97.com']
    start_urls = ['http://www.id97.com/movie']

    #专门用于解析二级子页面中的数据值
    def parseBySecondPage(self,response):
        actor = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[1]/td[2]/a/text()').extract_first()
        language = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[6]/td[2]/text()').extract_first()
        longTime = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[8]/td[2]/text()').extract_first()

        #取出Request方法的meta参数传递过来的字典(response.meta)
        item = response.meta['item']
        item['actor'] = actor
        item['language'] = language
        item['longTime'] = longTime
        #将item提交给管道
        yield item
    def parse(self, response):
        #名称,类型,导演,语言,片长
        div_list = response.xpath('/html/body/div[1]/div[1]/div[2]/div')
        for div in div_list:
            name = div.xpath('.//div[@class="meta"]/h1/a/text()').extract_first()
            #以下xpath方法返回的是一个列表,切列表元素为4
            kind = div.xpath('.//div[@class="otherinfo"]//text()').extract()
            #将kind列表转化成字符串
            kind = "".join(kind)
            url = div.xpath('.//div[@class="meta"]/h1/a/@href').extract_first()

            print(kind)
            #建立items对象
            item = MovieproItem()
            item['name'] = name
            item['kind'] = kind
            #问题:如何将剩下的电影详情数据存储到item对象(meta)
            #须要对url发起请求,获取页面数据,进行指定数据解析
            #meta参数只能够赋值一个字典(将item对象先封装到字典)
            yield scrapy.Request(url=url,callback=self.parseBySecondPage,meta={'item':item})


"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class MovieproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()
    kind = scrapy.Field()
    actor = scrapy.Field()
    language = scrapy.Field()
    longTime = scrapy.Field()

"""
pipelines.py
"""
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class MovieproPipeline(object):
    fp = None
    def open_spider(self,spider):
        self.fp = open('movie.txt','w',encoding='utf-8')
    def process_item(self, item, spider):
        detail = item['name']+':'+item['kind']+':'+item['actor']+':'+item['language']+':'+item['longTime']+'\n\n\n'
        self.fp.write(detail)
        return item
    def close_spider(self,spider):
        self.fp.close()


"""
settings.py
19行
22行
68行 开启管道
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
    'moviePro.pipelines.MovieproPipeline': 300,
}
请求传参

5、CrawlSpider

  • CrawlSpider实际上是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其本身独有的更增强大的特性和功能。其中最显著的功能就是”LinkExtractors连接提取器“。Spider是全部爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工做使用CrawlSpider更合适。
  • 爬取全站方法1:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法)【手动请求的发送】。
  • 爬取全站方法2:基于CrawlSpider的自动爬取进行实现(更加简洁和高效)。【推荐】

一、使用

  • 建立scrapy工程:scrapy startproject projectName
  • 建立爬虫文件:scrapy genspider -t crawl spiderName www.xxx.com (scrapy genspider -t crawl 爬虫名称 起始url)
  • 此指令对比之前的指令多了 "-t crawl",表示建立的爬虫文件是基于CrawlSpider这个类的,而再也不是Spider这个基类。

二、CrawlSpider总体爬取流程

  • a):爬虫文件首先根据起始url,获取该url的网页内容
  • b):连接提取器会根据指定提取规则将步骤a中网页内容中的连接进行提取
  • c):规则解析器会根据指定解析规则将连接提取器中提取到的连接中的网页内容根据指定的规则进行解析
  • d):将解析数据封装到item中,而后提交给管道进行持久化存储
  • LinkExtractor:连接提取器。- 做用:提取response中符合规则的连接。
  • Rule : 规则解析器。根据连接提取器中提取到的连接,根据指定规则提取解析器连接网页中的内容。

三、selenium在scrapy中的使用流程

  • a):重写爬虫文件的构造方法,在该方法中使用selenium实例化一个浏览器对象(由于浏览器对象只须要被实例化一次)
  • b):重写爬虫文件的closed(self,spider)方法,在其内部关闭浏览器对象。该方法是在爬虫结束时被调用
  • c):重写下载中间件的process_response方法,让该方法对响应对象进行拦截,并篡改response中存储的页面数据
  • d):在配置文件中开启下载中间件
  • 原理分析: 当引擎将url对应的请求提交给下载器后,下载器进行网页数据的下载, 而后将下载到的页面数据,封装到response中,提交给引擎,引擎将response在转交给Spiders。 Spiders接受到的response对象中存储的页面数据里是没有动态加载的新闻数据的。 要想获取动态加载的新闻数据,则须要在下载中间件中对下载器提交给引擎的response响应对象进行拦截, 切对其内部存储的页面数据进行篡改,修改为携带了动态加载出的新闻数据, 而后将被篡改的response对象最终交给Spiders进行解析操做。

四、下载中间件(Downloader Middlewares)

  • 下载中间件(Downloader Middlewares) 位于scrapy引擎和下载器之间的一层组件。
  • 做用:引擎将请求传递给下载器过程当中, 下载中间件能够对请求进行一系列处理。好比设置请求的 User-Agent,设置代理等
  • 做用:在下载器完成将Response传递给引擎中,下载中间件能够对响应进行一系列处理。好比进行gzip解压等。
  • 咱们主要使用下载中间件处理请求,通常会对请求设置随机的User-Agent ,设置随机的代理。目的在于防止爬取网站的反爬虫策略。

五、UA池:User-Agent池

  • 做用:尽量多的将scrapy工程中的请求假装成不一样类型的浏览器身份。
  • 操做流程:
    1. 在下载中间件中拦截请求
    2. 将拦截到的请求的请求头信息中的UA进行篡改假装
    3. 在配置文件中开启下载中间件

六、代理池

  • 做用:尽量多的将scrapy工程中的请求的IP设置成不一样的。
  • 操做流程:
    1. 在下载中间件中拦截请求
    2. 将拦截到的请求的IP修改为某一代理IP
    3. 在配置文件中开启下载中间件
"""
CrawlSpider

LinkExtractor:顾名思义,连接提取器。 - 做用:提取response中符合规则的连接。
LinkExtractor(
         allow=r'Items/',# 知足括号中“正则表达式”的值会被提取,若是为空,则所有匹配。
        deny=xxx,  # 知足正则表达式的则不会被提取。
             restrict_xpaths=xxx, # 知足xpath表达式的值会被提取
        restrict_css=xxx, # 知足css表达式的值会被提取
        deny_domains=xxx, # 不会被提取的连接的domains。 
    )
    
Rule : 规则解析器。根据连接提取器中提取到的连接,根据指定规则提取解析器连接网页中的内容。
     Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)
    - 参数介绍:
      参数1:指定连接提取器
      参数2:指定规则解析器解析数据的规则(回调函数)
      参数3:是否将连接提取器继续做用到连接提取器提取出的连接网页中。当callback为None,参数3的默认值为true。
rules=( ):指定不一样规则解析器。一个Rule对象表示一种提取规则。

"""
# -*- coding: utf-8 -*-
import scrapy
#导入CrawlSpider相关模块
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

#表示该爬虫程序是基于CrawlSpider类的
class ChoutiSpider(CrawlSpider):
    name = 'chouti'
    #allowed_domains = ['dig.chouti.com']
    start_urls = ['https://dig.chouti.com/']

    #连接提取器:用来提取指定的连接(url)
    #allow参数:赋值一个正则表达式
    #连接提取器就能够根据正则表达式在页面中提取指定的连接
    #提取到的连接会所有交给规则解析器

    # 实例化了一个连接提取器对象,且指定其提取规则
    link = LinkExtractor(allow=r'/all/hot/recent/\d+')

    #定义规则解析器,且指定解析规则经过callback回调函数
    rules = (
        #实例化了一个规则解析器对象
        #规则解析器接受了连接提取器发送的连接后,就会对这些连接发起请求,获取连接对应的页面内容,就会根据指定的规则对页面内容中指定的数据值进行解析
        #callback:指定一个解析规则(方法/函数)
        #follow:是否将连接提取器继续做用到链接提取器提取出的连接所表示的页面数据中
        Rule(link, callback='parse_item', follow=True),
    )

    #自定义规则解析器的解析规则函数
    def parse_item(self, response):
        print(response)

"""
settings.py
19行
22行
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False
CrawlSpider
# -*- coding: utf-8 -*-
import scrapy
from newsPro.items import NewsproItem
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class Chinanews(CrawlSpider):
    name = 'chinanews'
    # allowed_domains = ['http://www.chinanews.com/scroll-news/news1.html'] #中国新闻网(滚动新闻)
    start_urls = ['http://www.chinanews.com/scroll-news/news1.html',
                  'http://finance.chinanews.com/cj/gd.shtml'
                  ]
    custom_settings = {
        "ITEM_PIPELINES": {'newsPro.pipelines.NewsproPipeline': 300}
    }

    link = LinkExtractor(allow=r'http://www.chinanews.com/scroll-news/news\d+.html')
    link2 = LinkExtractor(allow=r'http://finance.chinanews.com/cj/gd.shtml')  # 中国新闻网(财经新闻)

    rules = (
        Rule(link, callback='parse_first', follow=True),
        Rule(link2, callback='parse_two', follow=True),
    )
    n=0

    def parse_first(self, response):
        li_list = response.xpath('/html/body//div[@class="content_list"]/ul/li')
        # print(len(li_list))
        for li in li_list:
            url = li.xpath('./div[@class="dd_bt"]/a/@href').extract_first()
            url="http:%s"%url
            # print(url)
            yield scrapy.Request(url=url, callback=self.parse_con,)

    def parse_two(self, response):
        li_list = response.xpath('/html/body//div[@class="content_list"]/ul/li')
        # print(len(li_list))
        for li in li_list:
            url = li.xpath('./div[@class="dd_bt"]/a/@href').extract_first()
            url="http://finance.chinanews.com%s"%url
            # print(url)
            yield scrapy.Request(url=url, callback=self.parse_con,)


    def parse_con(self, response):
        # self.n+=1
        # print(self.n)
        # print(response)
        div= response.xpath('/html/body//div[@id="cont_1_1_2"]')
        title =div.xpath('./h1/text()').extract_first()
        ctime_s =div.xpath('//div[@class="left-t"]/text()').extract_first().split("来源:")
        editor =div.xpath('./div[@class="left_name"]/div[@class="left_name"]/text()').extract_first()

        source =ctime_s[-1]
        ctime = ctime_s[0]

        content_list =div.xpath('./div[@class="left_zw"]/p/text()').extract()
        content = "".join(content_list)
        # print('=======', title, '=======')
        # print('=======', ctime,'=======')
        # print('=======', source, '=======')
        # print('=======', editor,  '=======')
        # print('=======',content, '=======')

        item = NewsproItem()
        item['title'] =title.strip()
        item['source'] =source.strip()
        item['content'] =content.strip()
        item['ctime'] =ctime.strip()
        item['editor'] =editor.strip()

        yield item
应用Chinanews

6、基于redis的分布式爬虫

一、分布式爬虫

  1. 概念:多台机器上能够执行同一个爬虫程序,实现网站数据的分布爬取。
  2. 原生的scrapy框架是否能够本身实现分布式?
    1. 不能够。
    2. 缘由1:由于多台机器上部署的scrapy会各自拥有各自的调度器,这样就使得多台机器没法分配start_urls列表中的url。(多台机器没法共享同一个调度器)
    3. 缘由2:多台机器爬取到的数据没法经过同一个管道对数据进行统一的数据持久出存储。(多台机器没法共享同一个管道)
  3. 安装scrapy-redis组件:
    • pip install scrapy-redis
  4. scrapy-redis组件:
    • scrapy-redis是基于scrapy框架开发出的一套组件,其做用就是可让scrapy实现分布式爬虫。
    • 使用scrapy-redis组件中封装好的调度器,将全部的url存储到该指定的调度器中,从而实现了多台机器的调度器共享。
    • 使用scrapy-redis组件中封装好的管道,将每台机器爬取到的数据存储经过该管道存储到redis数据库中,从而实现了多台机器的管道共享。

二、基于RedisCrawlSpider分布式爬取的流程

  1. redis配置文件的配置:
    1. win:redis.windows.conf linux:redis.conf
    2. 注释该行:bind 127.0.0.1,表示可让其余ip访问redis
    3. 将yes该为no:protected-mode no,表示可让其余ip操做redis,关闭保护模式
  2. redis服务器的开启:
    1. 基于配置配置文件
  3. 爬虫文件【区别】:
    1. 建立scrapy工程后,建立基于crawlSpider的爬虫文件
    2. 导入RedisCrawlSpider类(from scrapy_redis.spiders import RedisCrawlSpider),而后将爬虫文件修改为基于该类的源文件(class QiubaiSpider(RedisCrawlSpider):)
    3. 将start_url修改为redis_key = 'qiubaispider' # 调度器队列的名称 表示跟start_urls含义是同样
  4. 管道文件:
    1. 在配置文件中进行相应配置:将管道配置成scrapy-redis集成的管道
    2. 在scrapy-redis组件中已经帮助咱们封装好了一个专门用于链接存储redis数据库的管道(RedisPipeline),所以咱们直接使用便可,无需本身编写管道文件。
  5. 调度器:
    1. 在配置文件中将调度器切换成scrapy-redis集成好的调度器
  6. 配置文件:
    • 在settings.py中开启管道且将管道配置成scrapy-redis集成的管道。
    • 在settings.py中将调度器切换成scrapy-redis集成好的调度器
    • 该管道默认会链接且将数据存储到本机的redis服务中,若是想要链接存储到其余redis服务中须要在settings.py中进行配置
  7. 开启redis数据库的服务:
    1. redis-server 配置文件
  8. 执行爬虫程序:
    1. cd 到存放xxx.py的spiders目录
    2. scrapy runspider xxx.py
  9. redis客户端:
    1. 向调度器的队列中扔一个起始url (lpush 调度器队列的名称 “起始url”)lpush wangyi https://news.163.com
    2. ctrl + c 中止爬取
    3. keys * 查看
    4. lrange wangyi:items 0 -1 查看

三、基于RedisSpider的第二种形式的分布式爬虫(网易新闻)

  1. 其余配置和上面同样,只有爬虫文件不同
  2. 爬虫文件【区别】:
    1. 建立scrapy工程后,建立基于Spider的爬虫文件
    2. 导入RedisSpider类(from scrapy_redis.spiders import RedisSpider),而后将爬虫文件修改为基于该类的源文件(class WangyiSpider(RedisSpider):)
    3. 将start_url修改为redis_key = 'wangyi' 调度器队列名称

四、UA池:

  • 在中间件类中进行导包 from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
  • 封装一个基于UserAgentMiddleware的类,且重写该类的process_requests方法

五、代理池:

  • 注意请求url的协议后究竟是http仍是https

六、selenium如何被应用到scrapy:

  • 在爬虫文件中导入webdriver类
  • 在爬虫文件的爬虫类的构造方法中进行了浏览器实例化的操做
  • 在爬虫类的closed方法中进行浏览器关闭的操做
  • 在下载中间件的process_response方法中编写执行浏览器自动化的操做
"""
redis实现分布式基本流程
"""
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from redisPro.items import RedisproItem
#导入scrapy-redis中的模块
from scrapy_redis.spiders import RedisCrawlSpider
from redisPro.items import RedisproItem

class QiubaiSpider(RedisCrawlSpider):
    name = 'qiubai'
    #allowed_domains = ['https://www.qiushibaike.com/pic/']
    #start_urls = ['https://www.qiushibaike.com/pic/']

    #调度器队列的名称
    redis_key = 'qiubaispider'  #表示跟start_urls含义是同样

    #【注意】近期糗事百科更新了糗图板块的反爬机制,更新后该板块的页码连接/pic/page/2/s=5135066,
    # 末尾的数字每次页面刷新都会变化,所以正则不可写为/pic/page/\d+/s=5135066而应该修改为/pic/page/\d+
    link = LinkExtractor(allow=r'/pic/page/\d+')
    rules = (
        Rule(link, callback='parse_item', follow=True),
    )

    def parse_item(self, response):
       #将图片的url进行解析

        div_list = response.xpath('//*[@id="content-left"]/div')
        for div in div_list:
            img_url = div.xpath('./div[@class="thumb"]/a/img/@src').extract_first()
            item = RedisproItem()
            item['img_url'] = img_url

            yield item



"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class RedisproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    img_url = scrapy.Field()


"""
pipelines.py
"""
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class RedisproPipeline(object):
    def process_item(self, item, spider):
        return item



"""
settings.py
19行
22行
...管道
...调度器
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False


ITEM_PIPELINES = {
    #'redisPro.pipelines.RedisproPipeline': 300,
    'scrapy_redis.pipelines.RedisPipeline': 400,
}


# 使用scrapy-redis组件的去重队列
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
# 使用scrapy-redis组件本身的调度器
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
# 是否容许暂停
SCHEDULER_PERSIST = True

#若是redis服务器不在本身本机,则须要配置redis服务的ip和端口
REDIS_HOST = '172.20.10.7'  #redis数据库所在的机器上的ip地址
REDIS_PORT = 6379
#REDIS_PARAMS = {‘password’:’123456’}
RedisCrawlSpider实现分布式基本流程
"""
selenium在scrapy中的应用

from scrapy.http import HtmlResponse
    #参数介绍:
    #拦截到响应对象(下载器传递给Spider的响应对象)
    #request:响应对象对应的请求对象
    #response:拦截到的响应对象
    #spider:爬虫文件中对应的爬虫类的实例
    def process_response(self, request, response, spider):
        #响应对象中存储页面数据的篡改
        if request.url in['http://news.163.com/domestic/','http://news.163.com/world/','http://news.163.com/air/','http://war.163.com/']:
            spider.bro.get(url=request.url)
            js = 'window.scrollTo(0,document.body.scrollHeight)'
            spider.bro.execute_script(js)
            time.sleep(2)  #必定要给与浏览器必定的缓冲加载数据的时间
            #页面数据就是包含了动态加载出来的新闻数据对应的页面数据
            page_text = spider.bro.page_source
            #篡改响应对象
            return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding='utf-8',request=request)
        else:
            return response

"""
# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
from wangyiPro.items import WangyiproItem
from scrapy_redis.spiders import RedisSpider
class WangyiSpider(RedisSpider):
    name = 'wangyi'
    #allowed_domains = ['www.xxxx.com']
    #start_urls = ['https://news.163.com']
    redis_key = 'wangyi'

    def __init__(self):
        #实例化一个浏览器对象(实例化一次)
        self.bro = webdriver.Chrome(executable_path='/Users/bobo/Desktop/chromedriver')

    #必须在整个爬虫结束后,关闭浏览器
    def closed(self,spider):
        print('爬虫结束')
        self.bro.quit()

    def parse(self, response):
        lis = response.xpath('//div[@class="ns_area list"]/ul/li')
        indexs = [3,4,6,7]
        li_list = []  #存储的就是国内,国际,军事,航空四个板块对应的li标签对象
        for index in indexs:
            li_list.append(lis[index])
        #获取四个板块中的连接和文字标题
        for li in li_list:
            url = li.xpath('./a/@href').extract_first()
            title = li.xpath('./a/text()').extract_first()

            #print(url+":"+title)

            #对每个板块对应的url发起请求,获取页面数据(标题,缩略图,关键字,发布时间,url)
            yield scrapy.Request(url=url,callback=self.parseSecond,meta={'title':title})


    def parseSecond(self,response):
        div_list = response.xpath('//div[@class="data_row news_article clearfix "]')
        #print(len(div_list))
        for div in div_list:
            head = div.xpath('.//div[@class="news_title"]/h3/a/text()').extract_first()
            url = div.xpath('.//div[@class="news_title"]/h3/a/@href').extract_first()
            imgUrl = div.xpath('./a/img/@src').extract_first()
            tag = div.xpath('.//div[@class="news_tag"]//text()').extract()
            tags = []
            for t in tag:
                t = t.strip(' \n \t')
                tags.append(t)
            tag = "".join(tags)

            #获取meta传递过来的数据值title
            title = response.meta['title']

            #实例化item对象,将解析到的数据值存储到item对象中
            item = WangyiproItem()
            item['head'] = head
            item['url'] = url
            item['imgUrl'] = imgUrl
            item['tag'] = tag
            item['title'] = title

            #对url发起请求,获取对应页面中存储的新闻内容数据
            yield scrapy.Request(url=url,callback=self.getContent,meta={'item':item})
            #print(head+":"+url+":"+imgUrl+":"+tag)


    def getContent(self,response):
        #获取传递过来的item
        item = response.meta['item']

        #解析当前页面中存储的新闻数据
        content_list = response.xpath('//div[@class="post_text"]/p/text()').extract()
        content = "".join(content_list)
        item['content'] = content

        yield item


"""
items.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class WangyiproItem(scrapy.Item):
    # define the fields for your item here like:
    head = scrapy.Field()
    url = scrapy.Field()
    imgUrl = scrapy.Field()
    tag = scrapy.Field()
    title = scrapy.Field()
    content = scrapy.Field()


"""
pipelines.py
"""
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class WangyiproPipeline(object):
    def process_item(self, item, spider):
        print(item['title']+':'+item['content'])
        return item


"""
middlewares.py
"""
# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

from scrapy.http import HtmlResponse
import time
from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
import random
#UA池代码的编写(单独给UA池封装一个下载中间件的一个类)
#1,导包UserAgentMiddlware类
class RandomUserAgent(UserAgentMiddleware):

    def process_request(self, request, spider):
        #从列表中随机抽选出一个ua值
        ua = random.choice(user_agent_list)
        #ua值进行当前拦截到请求的ua的写入操做
        request.headers.setdefault('User-Agent',ua)

#批量对拦截到的请求进行ip更换
class Proxy(object):
    def process_request(self, request, spider):
        #对拦截到请求的url进行判断(协议头究竟是http仍是https)
        #request.url返回值:http://www.xxx.com
        h = request.url.split(':')[0]  #请求的协议头
        if h == 'https':
            ip = random.choice(PROXY_https)
            request.meta['proxy'] = 'https://'+ip
        else:
            ip = random.choice(PROXY_http)
            request.meta['proxy'] = 'http://' + ip

class WangyiproDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.



    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None
    #拦截到响应对象(下载器传递给Spider的响应对象)
    #request:响应对象对应的请求对象
    #response:拦截到的响应对象
    #spider:爬虫文件中对应的爬虫类的实例
    def process_response(self, request, response, spider):
        #响应对象中存储页面数据的篡改
        if request.url in['http://news.163.com/domestic/','http://news.163.com/world/','http://news.163.com/air/','http://war.163.com/']:
            spider.bro.get(url=request.url)
            js = 'window.scrollTo(0,document.body.scrollHeight)'
            spider.bro.execute_script(js)
            time.sleep(2)  #必定要给与浏览器必定的缓冲加载数据的时间
            #页面数据就是包含了动态加载出来的新闻数据对应的页面数据
            page_text = spider.bro.page_source
            #篡改响应对象
            return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding='utf-8',request=request)
        else:
            return response

PROXY_http = [
    '153.180.102.104:80',
    '195.208.131.189:56055',
]
PROXY_https = [
    '120.83.49.90:9000',
    '95.189.112.214:35508',
]

user_agent_list = [
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 "
        "(KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
        "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 "
        "(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 "
        "(KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 "
        "(KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 "
        "(KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 "
        "(KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
        "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 "
        "(KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
        "(KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 "
        "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 "
        "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
]




"""
settings.py
19行
22行
56开启下载中间件
...管道
"""
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

DOWNLOADER_MIDDLEWARES = {
    'wangyiPro.middlewares.WangyiproDownloaderMiddleware': 543,
    'wangyiPro.middlewares.RandomUserAgent': 542,
    'wangyiPro.middlewares.Proxy': 541,
}

ITEM_PIPELINES = {
    #'wangyiPro.pipelines.WangyiproPipeline': 300,
    'scrapy_redis.pipelines.RedisPipeline': 400,
}



#配置redis服务的ip和端口
REDIS_HOST = '172.20.10.7'  #redis数据库所在的机器上的ip地址
REDIS_PORT = 6379
#REDIS_PARAMS = {‘password’:’123456’}

# 使用scrapy-redis组件的去重队列
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
# 使用scrapy-redis组件本身的调度器
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
# 是否容许暂停
SCHEDULER_PERSIST = True
案例网易RedisSpider
相关文章
相关标签/搜索