基于Scrapy框架爬取ajax圖片并保存本地

先上一波福利

66347-2.jpg
66250-5.jpg
66158-3.jpg
68185.jpg
68205.jpg
俗話說:授人予魚不如授人以漁吱瘩,上代碼講解

項目結(jié)構(gòu)


WeChat74777e08e1d4298d3488d1c28ed68255.png

首先獲取到妹子圖的定位來獲取URL


屏幕快照 2020-06-20 上午11.44.27.png

右擊copy選擇Xpath就可以直接復制了

#找到妹子圖的鏈接
 url = response.xpath('//*[@id="home-collections"]/ul/li[4]/div/div[1]/a/@href').extract()[0] 

進入到下個頁面獲取頁面的全部URL,但是我發(fā)現(xiàn)是用ajax動態(tài)加載圖片的揍堰。
怎么獲得ajax信息獲取下一頁呢?
我們F12選擇Network,點擊XHR可以發(fā)現(xiàn)靜態(tài)文件


屏幕快照 2020-06-20 上午11.55.48.png

點擊滑到最下面,可以看到FormData的數(shù)據(jù)


屏幕快照 2020-06-20 上午11.57.08.png

沒錯捧弃,就是這數(shù)據(jù)
        for i in range(76):   #妹子圖一共有76頁
            formdata = {
                'type': 'collection29',
                'paged': str(i+1)   #paged是從1開始的
            }
            # Scrapy動態(tài)加載ajax請求,并使用回調(diào)函數(shù)進行深一層的爬取
            yield scrapy.FormRequest(url, callback=self.parse_page, formdata=formdata)

然后進入更深層次的挖掘,獲取到所有頁面上的URL


屏幕快照 2020-06-20 下午12.03.24.png
    def parse_page(self, response):
        urls = response.xpath('//*[@id="main"]/div[1]/div/div/div[1]/a/@href').extract() #獲取到當前頁面的全部url
        for url in urls:
      #使用回調(diào)函數(shù)進行深一層的爬取
            yield scrapy.Request(url, callback=self.parse_img)  

然后進入更深層次的挖掘擦囊,圖片標題的爬取,和每張圖片的爬取


屏幕快照 2020-06-20 下午12.07.23.png
    def parse_img(self, response):
        item = BeautifulgirlItem()
        name = response.xpath('//*[@id="post-single"]/h1/text()').extract()[0] #獲取到每個圖集的標題
        print(name)
        item['name'] = name
        img_urls = response.xpath('//*[@id="content-innerText"]/p/img/@src').extract() #獲取到每張圖片的URL
        for img_url in img_urls:
            item['img_url'] = img_url
            print(img_url)
            yield item

下面我把代碼整合一下
peibanni.py

# -*- coding: utf-8 -*-
import scrapy
from beautifulgirl.items import BeautifulgirlItem

class PeibanniSpider(scrapy.Spider):
    name = 'peibanni'
    allowed_domains = ['www.peibanni.com']
    start_urls = ['https://www.peibanni.com/']

    def parse(self, response):
        url = response.xpath('//*[@id="home-collections"]/ul/li[4]/div/div[1]/a/@href').extract()[0] #找到妹子圖的鏈接
        for i in range(76):
            formdata = {
                'type': 'collection29',
                'paged': str(I+1)
            }
            # Scrapy動態(tài)加載ajax請求,并使用回調(diào)函數(shù)進行深一層的爬取
            yield scrapy.FormRequest(url, callback=self.parse_page, formdata=formdata)

    def parse_page(self, response):
        urls = response.xpath('//*[@id="main"]/div[1]/div/div/div[1]/a/@href').extract() #獲取到當前頁面的全部url
        for url in urls:
            yield scrapy.Request(url, callback=self.parse_img)  #使用回調(diào)函數(shù)進行深一層的爬取

    def parse_img(self, response):
        item = BeautifulgirlItem()
        name = response.xpath('//*[@id="post-single"]/h1/text()').extract()[0] #獲取到每個圖集的標題
        print(name)
        item['name'] = name
        img_urls = response.xpath('//*[@id="content-innerText"]/p/img/@src').extract() #獲取到每張圖片的URL
        for img_url in img_urls:
            item['img_url'] = img_url
            print(img_url)
            yield item

接著是圖片數(shù)據(jù)的保存
在item.py中

import scrapy

class BeautifulgirlItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field() #圖片的名稱
    img_url = scrapy.Field() #圖片的URL

在pipeline中嘴办,使用內(nèi)置的圖片解析ImagesPipeline

import scrapy
from scrapy.pipelines.images import ImagesPipeline

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

class BeautifulgirlPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        #這個方法會循環(huán)執(zhí)行瞬场,前面每次傳入一個item,這個item就交給引擎
        #引擎又會交給管道來執(zhí)行涧郊,管道里有一系列的內(nèi)置方法贯被,這些方法會依次執(zhí)行
        yield scrapy.Request(url=item['img_url'], meta={'item':item})

    def file_path(self, request, response=None, info=None):
        item = request.meta['item']
        #獲取到每張圖片在URL中的名字,來達到去重到目的
        # 比如"https://www.peibanni.com/wp-content/uploads/2020/06/68215.jpg"妆艘,就獲取到了68215.jpg彤灶,
        img_tail = request.url.split('/')[-1]
        path = u'{0}/{1}'.format(item['name'],img_tail)
        return path

屏幕快照 2020-06-20 下午12.23.17.png

最后別忘記在setting.py中設置,
IMAGES_STORE不能拼錯,拼錯了就無法保存本地了批旺!

IMAGES_STORE = 'images'

setting.py的完整版

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

# Scrapy settings for beautifulgirl project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'beautifulgirl'

SPIDER_MODULES = ['beautifulgirl.spiders']
NEWSPIDER_MODULE = 'beautifulgirl.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'beautifulgirl (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15',
}


# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'beautifulgirl.middlewares.BeautifulgirlSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'beautifulgirl.middlewares.BeautifulgirlDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'beautifulgirl.pipelines.BeautifulgirlPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'


IMAGES_STORE = 'images'

如果覺得我寫的還不錯幌陕,就給我一個大大贊,你的支持是我的動力汽煮!

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末搏熄,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子暇赤,更是在濱河造成了極大的恐慌心例,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鞋囊,死亡現(xiàn)場離奇詭異止后,居然都是意外死亡,警方通過查閱死者的電腦和手機溜腐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進店門译株,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瓜喇,“玉大人,你說我怎么就攤上這事古戴∏烽伲” “怎么了?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵现恼,是天一觀的道長肃续。 經(jīng)常有香客問我,道長叉袍,這世上最難降的妖魔是什么始锚? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮喳逛,結(jié)果婚禮上瞧捌,老公的妹妹穿的比我還像新娘。我一直安慰自己润文,他們只是感情好姐呐,可當我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著典蝌,像睡著了一般曙砂。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上骏掀,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天鸠澈,我揣著相機與錄音,去河邊找鬼截驮。 笑死笑陈,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的葵袭。 我是一名探鬼主播涵妥,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼眶熬!你這毒婦竟也來了妹笆?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤娜氏,失蹤者是張志新(化名)和其女友劉穎拳缠,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贸弥,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡窟坐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片哲鸳。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡臣疑,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出徙菠,到底是詐尸還是另有隱情讯沈,我是刑警寧澤,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布婿奔,位于F島的核電站缺狠,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏萍摊。R本人自食惡果不足惜挤茄,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望冰木。 院中可真熱鬧穷劈,春花似錦、人聲如沸踊沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽逼龟。三九已至练湿,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間审轮,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工辽俗, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留疾渣,地道東北人。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓崖飘,卻偏偏與公主長得像榴捡,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子朱浴,可洞房花燭夜當晚...
    茶點故事閱讀 45,507評論 2 359