天天看點

20、 Python快速開發分布式搜尋引擎Scrapy精講—編寫spiders爬蟲檔案循環抓取内容—meta屬性傳回指定值給回調函數—Scrapy内置圖檔下載下傳器

編寫spiders爬蟲檔案循環抓取内容

Request()方法,将指定的url位址添加到下載下傳器下載下傳頁面,兩個必須參數,

  參數:

  url='url'

  callback=頁面處理函數

  使用時需要yield Request()

parse.urljoin()方法,是urllib庫下的方法,是自動url拼接,如果第二個參數的url位址是相對路徑會自動與第一個參數拼接

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request                             #導入url傳回給下載下傳器的方法
from urllib import parse                                    #導入urllib庫裡的parse子產品

class PachSpider(scrapy.Spider):
    name = 'pach'
    allowed_domains = ['blog.jobbole.com']                  #起始域名
    start_urls = ['http://blog.jobbole.com/all-posts/']     #起始url

    def parse(self, response):
        """
        擷取清單頁的文章url位址,交給下載下傳器
        """
        #擷取目前頁文章url
        lb_url = response.xpath('//a[@class="archive-title"]/@href').extract()  #擷取文章清單url
        for i in lb_url:
            # print(parse.urljoin(response.url,i))                                             #urllib庫裡的parse子產品的urljoin()方法,是自動url拼接,如果第二個參數的url位址是相對路徑會自動與第一個參數拼接
            yield Request(url=parse.urljoin(response.url, i), callback=self.parse_wzhang)      #将循環到的文章url添加給下載下傳器,下載下傳後交給parse_wzhang回調函數

        #擷取下一頁清單url,交給下載下傳器,傳回給parse函數循環
        x_lb_url = response.xpath('//a[@class="next page-numbers"]/@href').extract()         #擷取下一頁文章清單url
        if x_lb_url:
            yield Request(url=parse.urljoin(response.url, x_lb_url[0]), callback=self.parse)     #擷取到下一頁url傳回給下載下傳器,回調給parse函數循環進行

    def parse_wzhang(self,response):
        title = response.xpath('//div[@class="entry-header"]/h1/text()').extract()           #擷取文章标題
        print(title)           
20、 Python快速開發分布式搜尋引擎Scrapy精講—編寫spiders爬蟲檔案循環抓取内容—meta屬性傳回指定值給回調函數—Scrapy内置圖檔下載下傳器

Request()函數在傳回url時,同時可以通過meta屬性傳回一個自定義字典給回調函數

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request                             #導入url傳回給下載下傳器的方法
from urllib import parse                                    #導入urllib庫裡的parse子產品
from adc.items import AdcItem                               #導入items資料接收子產品的接收類

class PachSpider(scrapy.Spider):
    name = 'pach'
    allowed_domains = ['blog.jobbole.com']                  #起始域名
    start_urls = ['http://blog.jobbole.com/all-posts/']     #起始url

    def parse(self, response):
        """
        擷取清單頁的文章url位址,交給下載下傳器
        """
        #擷取目前頁文章url
        lb = response.css('div .post.floated-thumb')  #擷取文章清單區塊,css選擇器
        # print(lb)
        for i in lb:
            lb_url = i.css('.archive-title ::attr(href)').extract_first('')     #擷取區塊裡文章url
            # print(lb_url)

            lb_img = i.css('.post-thumb img ::attr(src)').extract_first('')     #擷取區塊裡文章縮略圖
            # print(lb_img)

            yield Request(url=parse.urljoin(response.url, lb_url), meta={'lb_img':parse.urljoin(response.url, lb_img)}, callback=self.parse_wzhang)      #将循環到的文章url添加給下載下傳器,下載下傳後交給parse_wzhang回調函數

        #擷取下一頁清單url,交給下載下傳器,傳回給parse函數循環
        x_lb_url = response.css('.next.page-numbers ::attr(href)').extract_first('')         #擷取下一頁文章清單url
        if x_lb_url:
            yield Request(url=parse.urljoin(response.url, x_lb_url), callback=self.parse)     #擷取到下一頁url傳回給下載下傳器,回調給parse函數循環進行

    def parse_wzhang(self,response):
        title = response.css('.entry-header h1 ::text').extract()           #擷取文章标題
        # print(title)

        tp_img = response.meta.get('lb_img', '')                            #接收meta傳過來的值,用get擷取防止出錯
        # print(tp_img)

        shjjsh = AdcItem()                                                                   #執行個體化資料接收類
        shjjsh['title'] = title                                                              #将資料傳輸給items接收子產品的指定類
        shjjsh['img'] = tp_img

        yield shjjsh                                #将接收對象傳回給pipelines.py處理子產品           
    • *

Scrapy内置圖檔下載下傳器使用

Scrapy給我們内置了一個圖檔下載下傳器在crapy.pipelines.images.ImagesPipeline,專門用于将爬蟲抓取到圖檔url後将圖檔下載下傳到本地

第一步、爬蟲抓取圖檔URL位址後,填充到 items.py檔案的容器函數

  爬蟲檔案

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request                             #導入url傳回給下載下傳器的方法
from urllib import parse                                    #導入urllib庫裡的parse子產品
from adc.items import AdcItem                               #導入items資料接收子產品的接收類

class PachSpider(scrapy.Spider):
    name = 'pach'
    allowed_domains = ['blog.jobbole.com']                  #起始域名
    start_urls = ['http://blog.jobbole.com/all-posts/']     #起始url

    def parse(self, response):
        """
        擷取清單頁的文章url位址,交給下載下傳器
        """
        #擷取目前頁文章url
        lb = response.css('div .post.floated-thumb')  #擷取文章清單區塊,css選擇器
        # print(lb)
        for i in lb:
            lb_url = i.css('.archive-title ::attr(href)').extract_first('')     #擷取區塊裡文章url
            # print(lb_url)

            lb_img = i.css('.post-thumb img ::attr(src)').extract_first('')     #擷取區塊裡文章縮略圖
            # print(lb_img)

            yield Request(url=parse.urljoin(response.url, lb_url), meta={'lb_img':parse.urljoin(response.url, lb_img)}, callback=self.parse_wzhang)      #将循環到的文章url添加給下載下傳器,下載下傳後交給parse_wzhang回調函數

        #擷取下一頁清單url,交給下載下傳器,傳回給parse函數循環
        x_lb_url = response.css('.next.page-numbers ::attr(href)').extract_first('')         #擷取下一頁文章清單url
        if x_lb_url:
            yield Request(url=parse.urljoin(response.url, x_lb_url), callback=self.parse)     #擷取到下一頁url傳回給下載下傳器,回調給parse函數循環進行

    def parse_wzhang(self,response):
        title = response.css('.entry-header h1 ::text').extract()           #擷取文章标題
        # print(title)

        tp_img = response.meta.get('lb_img', '')                            #接收meta傳過來的值,用get擷取防止出錯
        # print(tp_img)

        shjjsh = AdcItem()                                                                   #執行個體化資料接收類
        shjjsh['title'] = title                                                              #将資料傳輸給items接收子產品的指定類
        shjjsh['img'] = [tp_img]

        yield shjjsh                                #将接收對象傳回給pipelines.py處理子產品           

第二步、設定 items.py 檔案的容器函數,接收爬蟲擷取到的資料填充

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

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

import scrapy

#items.py,檔案是專門用于,接收爬蟲擷取到的資料資訊的,就相當于是容器檔案

class AdcItem(scrapy.Item):    #設定爬蟲擷取到的資訊容器類
    title = scrapy.Field()     #接收爬蟲擷取到的title資訊
    img = scrapy.Field()       #接收縮略圖
    img_tplj = scrapy.Field()  #圖檔儲存路徑           

第三步、在pipelines.py使用crapy内置的圖檔下載下傳器

1、首先引入内置圖檔下載下傳器

2、自定義一個圖檔下載下傳内,繼承crapy内置的ImagesPipeline圖檔下載下傳器類

3、使用ImagesPipeline類裡的item_completed()方法擷取到圖檔下載下傳後的儲存路徑

4、在settings.py設定檔案裡,注冊自定義圖檔下載下傳器類,和設定圖檔儲存路徑

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.pipelines.images import ImagesPipeline  #導入圖檔下載下傳器子產品

class AdcPipeline(object):                      #定義資料處理類,必須繼承object
    def process_item(self, item, spider):       #process_item(item)為資料處理函數,接收一個item,item裡就是爬蟲最後yield item 來的資料對象
        print('文章标題是:' + item['title'][0])
        print('文章縮略圖url是:' + item['img'][0])
        print('文章縮略圖儲存路徑是:' + item['img_tplj'])  #接收圖檔下載下傳器填充的,圖檔下載下傳後的路徑

        return item

class imgPipeline(ImagesPipeline):                      #自定義一個圖檔下載下傳内,繼承crapy内置的ImagesPipeline圖檔下載下傳器類
    def item_completed(self, results, item, info):      #使用ImagesPipeline類裡的item_completed()方法擷取到圖檔下載下傳後的儲存路徑
        for ok, value in results:
            img_lj = value['path']     #接收圖檔儲存路徑
            # print(ok)
            item['img_tplj'] = img_lj  #将圖檔儲存路徑填充到items.py裡的字段裡
        return item                    #将item給items.py 檔案的容器函數

    #注意:自定義圖檔下載下傳器設定好後,需要在           

在settings.py設定檔案裡,注冊自定義圖檔下載下傳器類,和設定圖檔儲存路徑

IMAGES_URLS_FIELD 設定要下載下傳圖檔的url位址,一般設定的items.py裡接收的字段

IMAGES_STORE 設定圖檔儲存路徑

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'adc.pipelines.AdcPipeline': 300,  #注冊adc.pipelines.AdcPipeline類,後面一個數字參數表示執行等級,
   'adc.pipelines.imgPipeline': 1,    #注冊自定義圖檔下載下傳器,數值越小,越優先執行
}

IMAGES_URLS_FIELD = 'img'                             #設定要下載下傳圖檔的url字段,就是圖檔在items.py裡的字段裡
lujin = os.path.abspath(os.path.dirname(__file__))
IMAGES_STORE = os.path.join(lujin, 'img')             #設定圖檔儲存路徑           
20、 Python快速開發分布式搜尋引擎Scrapy精講—編寫spiders爬蟲檔案循環抓取内容—meta屬性傳回指定值給回調函數—Scrapy内置圖檔下載下傳器

【轉載自:

http://www.lqkweb.com