目录
scrapy爬52古装网高清壁纸并下载
/    

scrapy爬52古装网高清壁纸并下载

1. 创建项目

# 创建爬虫项目
scrapy startproject GuzhuangWallpaper

# 进入爬虫项目的目录,生成爬虫文件(模板)
scrapy genspider guzhuang www.52guzhuang.com

2. setting文件的配置

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

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

BOT_NAME = 'GuzhuangWallpaper'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

LOG_LEVEL = 'WARNING'

# 设置下载参数
# FILES_STORE = "D:"  # 文件的存储路径
IMAGES_STORE = "/media/nianshao/59D5FCE97201B8A7/download02/古装壁纸"  # 图片的存储路径
# 避免下载最近90天已经下载过的文件内容
FILES_EXPIRES = 90
# 避免下载最近90天已经下载过的图像内容
IMAGES_EXPIRES = 0
# 设置图片缩略图
IMAGES_THUMBS = {
    'small': (50, 50),
    'big': (250, 250)
}
#该字段的值为xxxItem中定义的存储图片链接的img_urls字段
IMAGES_URLS_FIELD = "img_urls"
# 该字段的值为xxxItem中定义的存储图片信息的imgages字段
IMAGES_RESULT_FIELD = "images"

# 图片过滤器,最小高度和宽度,低于此尺寸不下载
IMAGES_MIN_HEIGHT = 110
IMAGES_MIN_WIDTH = 110

# 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://doc.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',
  'Accept-Language': 'en',
  'Referer': 'http://www.52guzhuang.com/forum-59-2.html',
    'Cookie': '8ZxE_2132_saltkey=It2jtbtX; 8ZxE_2132_lastvisit=1566439893; bdshare_firstime=1566443802012; 8ZxE_2132_atarget=1; security_session_verify=27962fc0952df38b5fd0b1dd5d5b4097; ZDEDebuggerPresent=php,phtml,php3; Qs_lvt_192466=1566443795%2C1566632328; 8ZxE_2132_visitedfid=59D45; 8ZxE_2132_st_t=0%7C1566645295%7C7bc18059531f8726ac78d0664c62a87a; 8ZxE_2132_forum_lastvisit=D_45_1566643250D_59_1566645295; 8ZxE_2132_viewid=tid_58630; 8ZxE_2132_st_p=0%7C1566645504%7C2616708e5e9e0d761d5c513cf26d362a; 8ZxE_2132_sendmail=1; Qs_pv_192466=220429305054871900%2C4055271188718522400%2C577107211184728000%2C1215782351179700500%2C3219074084875213300; 8ZxE_2132_lastact=1566645606%09forum.php%09ajax',
    'Host': 'www.52guzhuang.com',
    'Pragma': 'no-cache',
    'Upgrade-Insecure-Requests': 1,
    'User-Agent': 'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14',

}

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

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

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

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'scrapy.pipelines.images.ImagesPipeline': 1,
   'GuzhuangWallpaper.pipelines.GuzhuangwallpaperPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.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://doc.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'

3. 爬虫文件的编写

  • 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 GuzhuangwallpaperItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    img_urls = scrapy.Field()  # 固定字段 与 setting中的一致


  • 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 scrapy
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline  # 内置的图片通道


class GuzhuangwallpaperPipeline(ImagesPipeline):

    def item_completed(self, results, item, info):
        image_path = [x['path'] for ok, x in results if ok]
        if not image_path:
            raise DropItem('Item contains no images')
        item['image_paths'] = image_path
        return item

    def process_item(self, item, spider):
        print("正在下载", item['img_urls'])

        pass

  • guzhuang.py
# -*- coding: utf-8 -*-
import scrapy
from ..items import GuzhuangwallpaperItem
from time import sleep


class GuzhuangSpider(scrapy.Spider):
    name = 'guzhuang'
    allowed_domains = ['www.52guzhuang.com']
    start_urls = ['http://www.52guzhuang.com/forum-59-1.html']

    def __init__(self):
        self.base_url = "http://www.52guzhuang.com/"

    def parse(self, response):
        urls = response.xpath('//div[@class="v-meta-title"]/a[1]/@href').extract()
        for url in urls:
            yield scrapy.Request(url, callback=self.get_picture, )
            # break
            # sleep(1)
        # next_page = response.xpath('//a[@class="nxt"]/text()[last()]').extract_first()
        # if next_page == '下一页':
        #     href = response.xpath('//a[@class="nxt"]/@href[last()]').extract_first()
        #     yield scrapy.Request(self.base_url + href, callback=self.parse, )

    def get_picture(self, response):
        item = GuzhuangwallpaperItem()
        img_urls = response.xpath('//img[@class="zoom"]/@file').extract()
        next_page = response.xpath('//div[@class="pg"]/a[last()]/text()').extract_first()
        for url in img_urls:
            item['img_urls'] = [self.base_url + url]
            print(url)
            yield item
        if next_page == '下一页':
            href = response.xpath('//div[@class="pg"]/a[last()]/@href').extract_first()
            pic_url = self.base_url + href
            yield scrapy.Request(pic_url, callback=self.get_picture)
            # sleep(1)



4. 运行爬虫

scrapy crawl guzhuang

标题:scrapy爬52古装网高清壁纸并下载
作者:gitsilence
地址:https://blog.lacknb.cn/articles/2019/08/26/1577974158774.html