scrapy框架学习

 -  一 什么是scrapy?

   - Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架,非常出名,非常强悍。所谓的框架就是一个已经被集成了各种功能(高性能异步下载,队列,分布式,解析,持久化等)的具有很强通用性的项目模板。

   - 安装

     - linux: pip3 install scrapy

     - windows:

       - 1) pip3 install wheel

       - 2) 下载Twisted (http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted)

       - 3) 进入下载目录,  执行 pip3 install  Twisted‑17.1.0‑cp35‑cp35m‑win_amd64.whl

       - 4) pip3 install pywin32

       - 5) pip3 install scrapy

 -  二 使用

   - 1) 创建项目:scrapy startproject 项目名称

   - 2) 创建应用程序:

     - 先进入项目目录:  cd  项目名

     - scrapy genspider 应用名  爬取网页的起始url:

     - 生成的初始文件

# -*- coding: utf-8 -*-
import scrapy


class SpidermanSpider(scrapy.Spider):
    name = 'spiderman'  #应用名称
    #允许爬取的域名(如果遇到非该域名的url则爬取不到数据)
    allowed_domains = ['www.xxx.com']
    #起始爬取的url
    start_urls = ['http://www.xxx.com/']
    
    #访问起始URL并获取结果后的回调函数,该函数的response参数就是向起始的url发送请求后,获取的响应对象.该函数返回值必须为可迭代对象或者NUll 
    def parse(self, response):
        pass

      - settings.py基础配置文件设置:

 #  USER_AGENT =  ""  伪装请求载体身份

 #  ROBOTSTXT_OBEY = False  可以忽略或者不遵守robots协议

      - 简单爬取示例

# -*- coding: utf-8 -*-
import scrapy


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

    def parse(self, response):
        #xpath为response中的方法,可以将xpath表达式直接作用于该函数中
        div_list = response.xpath('//div[@id="content-left"]/div')
        for div in div_list:
            #xpath函数返回的为列表,列表中存放的数据为Selector类型的数据。我们解析到的内容被封装在了Selector对象中,需要调用extract()函数将解析的内容从Selecor中取出。
            author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
            content = div.xpath('./a[1]/div/span//text()').extract()
            content = "".join(content)
            print(author,content)

   - 执行代码命令 : scrapy crawl  上面类中的name  (--nolog) 是否显示日志

 - 三 scrapy 框架持久化存储

       - 1 )基于终端指令的持久化存储

# -*- coding: utf-8 -*-
import scrapy


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

    def parse(self, response):
        div_list = response.xpath('//div[@id="content-left"]/div')
        all_data = []
        for div in div_list:
            author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
            content = div.xpath('./a[1]/div/span//text()').extract()
            content = "".join(content)

            dic = {
                "author":author,
                "content":content
            }

            all_data.append(dic)

        return all_data
View Code

     - 执行输出指定格式进行存储:将爬取到的数据写入不同格式的文件中进行存储

        - 执行命令 : 

scrapy crawl 爬虫名称  -o  xxxx.csv  
                              .xml
                              .json

   - 2 )基于管道的持久化存储

      - scrapy框架中已经为我们专门集成好了高效、便捷的持久化操作功能,我们直接使用即可。

    items.py:数据结构模板文件。定义数据属性。
    pipelines.py:管道文件。接收数据(items),进行持久化操作。

持久化流程:
    1.爬虫文件爬取到数据后,需要将数据封装到items对象中。
    2.使用yield关键字将items对象提交给pipelines管道进行持久化操作。
    3.在管道文件中的process_item方法中接收爬虫文件提交过来的item对象,然后编写持久化存储的代码将item对象中存储的数据进行持久化存储
    4.settings.py配置文件中开启管道

     - 爬取Boss网

# -*- coding: utf-8 -*-
import scrapy

from test222.items import Test222Item
class SpidermanSpider(scrapy.Spider):
    name = 'spiderman'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.zhipin.com/c101010100/?query=python爬虫&page=1&ka=page-2']
    # 解析+管道持久化存储
    def parse(self, response):
        li_list = response.xpath('//div[@class="job-list"]/ul/li')
        for li in li_list:
            job_name = li.xpath('.//div[@class="info-primary"]/h3/a/div/text()').extract_first()
            salary = li.xpath('.//div[@class="info-primary"]/h3/a/span/text()').extract_first()
            company = li.xpath('.//div[@class="company-text"]/h3/a/text()').extract_first()
            # 实例化一个item对象
            item = Test222Item()
            # 将解析到的数据全部封装到item对象中
            item["job_name"] = job_name
            item['salary'] = salary
            item['company'] = company

            yield item
spiderman
import scrapy


class Test222Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    job_name = scrapy.Field()
    salary = scrapy.Field()
    company = scrapy.Field()
items
class Test222Pipeline(object):
    fp = None
    def open_spider(self,spider):
        print("start....")
        self.fp = open("./boss.txt","w",encoding="utf-8")
    def close_spider(self,spider):
        print("close....")
        self.fp.close()

    # 爬虫文件每向管道提交一次item,则该方法就会被调用一次.
    # 参数:item 就是管道接收到的item类型对象
    def process_item(self, item, spider):
        print(item)
        self.fp.write(item["job_name"] + ":" + item["salary"] + ":" + item["company"] + "
")
        return item
pipelines
# settings.py

ITEM_PIPELINES = {
   'test222.pipelines.Test222Pipeline': 300,
}

     - 执行 scrapy crawl spiderman 生成 boss.txt文件

   - 3) 基于mysql的管道存储

     - 上述案例在管道文件将item对象中的数据值存储到了磁盘中,如果将item数据写入mysql数据库的话,只需要将上述案例中的管道文件修改即可:

import pymysql
class Test222Pipeline(object):
    fp = None
    def open_spider(self,spider):
        print("start....")
        self.fp = open("./boss.txt","w",encoding="utf-8")
    def close_spider(self,spider):
        print("close....")
        self.fp.close()

    # 爬虫文件每向管道提交一次item,则该方法就会被调用一次.
    # 参数:item 就是管道接收到的item类型对象
    def process_item(self, item, spider):
        print(item)
        self.fp.write(item["job_name"] + ":" + item["salary"] + ":" + item["company"] + "
")
        return item


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",
            password="",
            db="scrapy",
            charset="utf8")
        print(self.conn)
    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute('insert into boss values ("%s","%s","%s")' % (item['job_name'], item['salary'], item['company']))
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
    def close_spider(self,spider):
        self.conn.close()
        self.cursor.close()
pipelines.py
# settings.py

ITEM_PIPELINES = {
   # 'test222.pipelines.Test222Pipeline': 300,
   'test222.pipelines.mysqlPipeline': 301,
}

   - 4) 基于redis的管道存储

     - 同样redis只需要修改如下代码:

class redisPipeline(object):
    conn = None
    def open_spider(self,spider):
        self.conn = Redis(host="127.0.0.1",port=6379)
        print(self.conn)
    def process_item(self, item, spider):
        dic = {
            'name':item["job_name"],
            'salary':item["salary"],
            "company":item["company"]
        }
        self.conn.lpush("boss",dic)
spiderman.py
ITEM_PIPELINES = {
   # 'test222.pipelines.Test222Pipeline': 300,
   # 'test222.pipelines.mysqlPipeline': 301,
   'test222.pipelines.redisPipeline': 302,
}

    - 5)分页 scrapy.Request

# -*- coding: utf-8 -*-
import scrapy

from test222.items import Test222Item
class SpidermanSpider(scrapy.Spider):
    name = 'spiderman'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.zhipin.com/job_detail/?query=python%E7%88%AC%E8%99%AB&scity=101010100&industry=&position=']

    url = "https://www.zhipin.com/c101010100/?query=python爬虫&page=%d&ka=page-2"
    page = 1
    # 解析+管道持久化存储
    def parse(self, response):
        li_list = response.xpath('//div[@class="job-list"]/ul/li')
        for li in li_list:
            job_name = li.xpath('.//div[@class="info-primary"]/h3/a/div/text()').extract_first()
            salary = li.xpath('.//div[@class="info-primary"]/h3/a/span/text()').extract_first()
            company = li.xpath('.//div[@class="company-text"]/h3/a/text()').extract_first()
            # 实例化一个item对象
            item = Test222Item()
            # 将解析到的数据全部封装到item对象中
            item["job_name"] = job_name
            item['salary'] = salary
            item['company'] = company

            yield item
        if self.page <=3:
            self.page +=1
            new_url = format(self.url%self.page)
            print(new_url)

            # 手动请求发送
            yield scrapy.Request(url=new_url,callback=self.parse)
spiderman

 - 四 post请求

# -*- coding: utf-8 -*-
import scrapy

class PostSpider(scrapy.Spider):
    name = 'post'
    allowed_domains = ['www.xxx.con']
    start_urls = ['https://fanyi.baidu.com/sug'] # post请求的url

    def start_requests(self):  # 当start_urls是Post请求url时 必须重写start_requests
        data = {
            "kw":"dog"
        }
        for url in self.start_urls:
            yield  scrapy.FormRequest(url=url,formdata=data,callback=self.parse)

    def parse(self, response):
        print(response.text)

 - 五 请求传参和日志等级

   - 1) 请求传参

    - 在某些情况下,我们爬取的数据不在同一个页面中,例如,我们爬取一个电影网站,电影的名称,评分在一级页面,而要爬取的其他电影详情在其二级子页面中。这时我们就需要用到请求传参。

# -*- coding: utf-8 -*-
import scrapy
from test222.items import Test222Item

class MovieSpider(scrapy.Spider):
    name = 'movie'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.4567tv.tv/frim/index1.html']

    def parse_detail(self, response):
        # response.meta返回接收到的meta字典
        item = response.meta["item"]
        actor = response.xpath('/html/body/div[1]/div/div/div/div[2]/p[3]/a/text()').extract_first()
        item["actor"] = actor

        yield item
    def parse(self, response):
        li_list = response.xpath('//li[@class="col-md-6 col-sm-4 col-xs-3"]')
        print("111111")
        for li in li_list:
            item = Test222Item()

            name = li.xpath('./div/a/@title').extract_first()
            detail_url = 'https://www.4567tv.tv' + li.xpath('./div/a/@href').extract_first()
            item["name"] = name
            # meta参数:请求传参.meta字典就会传递给回调函数的response参数
            yield scrapy.Request(url=detail_url,callback=self.parse_detail,meta={"item":item})
spiders.movie
import scrapy


class Test222Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()
    actor = scrapy.Field()
items
#settings:

ITEM_PIPELINES = {
   'test222.pipelines.Test222Pipeline': 300,
}

     - 最后在管道处查看item即可

    - 2) 日志等级  (settings文件)

     - 终端执行后 如果有错则会输出错误信息,如果没有,正常执行

LOG_LEVEL = "ERROR"

     - 文件存储  (存储到指定文件)

LOG_FILE = "./log.txt"

  - 六 五大核心组件工作流程

     -  1 引擎(Scrapy)

       - 用来处理整个系统的数据流处理, 触发事务(框架核心)

     -  2 调度器(Scheduler)

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

     -  3 下载器(Downloader)

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

     -  4  爬虫(Spider)

       - 爬虫是主要干活的, 用于从特定的网页中提取自己需要的信息, 即所谓的实体(Item)。用户也可以从中提取出链接,让Scrapy继续抓取下一个页面

     -  5  项目管道(Pipeline)

       - 负责处理爬虫从网页中抽取的实体,主要的功能是持久化实体、验证实体的有效性、清除不需要的信息。当页面被爬虫解析后,将被发送到项目管道,并经过几个特定的次序处理数据。

# -*- 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
import random

class MiddleproDownloaderMiddleware(object):
    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"
    ]
    # 可被选用的代理IP
    PROXY_http = [
        '153.180.102.104:80',
        '195.208.131.189:56055',
    ]
    PROXY_https = [
        '120.83.49.90:9000',
        '95.189.112.214:35508',
    ]
   #拦截所有未发生异常的请求
    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

        #使用UA池进行请求的UA伪装
        print('this is process_request')
        request.headers['User-Agent'] = random.choice(self.user_agent_list)
        print(request.headers['User-Agent'])

        # #使用代理池进行请求代理ip的设置
        # if request.url.split(':')[0] == 'http':
        #     request.meta['proxy'] = random.choice(self.PROXY_http)
        # else:
        #     request.meta['proxy'] = random.choice(self.PROXY_https)
        return None
    #拦截所有的响应
    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response
    #拦截到产生异常的请求
    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        # 使用代理池进行请求代理ip的设置
        print('this is process_exception!')
        if request.url.split(':')[0] == 'http':
            request.meta['proxy'] = random.choice(self.PROXY_http)
        else:
            request.meta['proxy'] = random.choice(self.PROXY_https)
middlewares.py

  - 七 scrapy中应用selenium

在scrapy中使用selenium的编码流程:
    1.在spider的构造方法中创建一个浏览器对象(作为当前spider的一个属性)
    2.重写spider的一个方法closed(self,spider),在该方法中执行浏览器关闭的操作
    3.在下载中间件的process_response方法中,通过spider参数获取浏览器对象
    4.在中间件的process_response中定制基于浏览器自动化的操作代码(获取动态加载出来的页面源码数据)
    5.实例化一个响应对象,且将page_source返回的页面源码封装到该对象中
    6.返回该新的响应对象
from scrapy import signals
from scrapy.http import HtmlResponse
from time import sleep

class Test333DownloaderMiddleware(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

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        # 获取动态加载出来的数据
        bro = spider.bro
        bro.get(url=request.url)
        sleep(3)
        bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')
        # 包含了动态加载出来的新闻数据
        page_text = bro.page_source
        sleep(3)
        return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding="utf-8",request=request)

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass
middlewares.py
# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver

class WangyiSpider(scrapy.Spider):
    name = 'wangyi'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['http://war.163.com/']

    def __init__(self):
        self.bro = webdriver.Chrome(executable_path=r'D:pathon 课程123爬虫s15day137s15day137爬虫day_03_爬虫chromedriver.exe')

    def parse(self, response):
        div_list = response.xpath('//div[@class="data_row news_article clearfix "]')
        for div in div_list:
            title = div.xpath('.//div[@class="news_title"]/h3/a/text()').extract_first()
            print(title)

    def close(self, spider):
        print("关闭")
        self.bro.quit()
spiders.wangyi
# settings:

DOWNLOADER_MIDDLEWARES = {
   'test333.middlewares.Test333DownloaderMiddleware': 543,
}

  - 八 如何提升scrapy爬取数据的i效率:

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

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

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

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

减少下载超时:
    如果对一个非常慢的链接进行爬取,减少下载超时可以能让卡住的链接快速被放弃,从而提升效率。在配置文件中进行

  

原文地址:https://www.cnblogs.com/lzmdbk/p/10456712.html