scrapy 爬取图片

1.scrapy 有下载图片的自带接口,不用我们在去实现

setting.py设置

# 保存log信息的文件名
LOG_LEVEL = "INFO"
# LOG_STDOUT = True
# LOG_ENCODING = 'utf-8'
# # 路径  os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
# LOG_FILE = "info.log"

# 下载延迟
import random
DOWNLOAD_DELAY = random.random() + random.random()
RANDOMIZE_DOWNLOAD_DELAY = True

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'

# 图片下载路径
import os
BASE_DIR = os.path.dirname((os.path.abspath(__file__)))
MEDIA_ALLOW_REDIRECTS = True
IMAGES_STORE = os.path.join(BASE_DIR, "images")

# 在配置文件settings.py中设置IMAGES_THUMBS,它是一个字典,每一项的值是缩略图的尺寸。 开启这个功能后,下载一张图片时,本地会出现3张图片,1张原图片,2张缩略图。
IMAGES_THUMBS = {
    'small': (50, 50),
    'big': (270, 270),
}

# 设置图文件过期时间   30天
IMAGES_EXPIRES = 30
# 在配置文件settings.py中设置IMAGES_MIN_HEIGHT和IMAGES_MIN_WIDTH,它们分别指定需要过滤掉的最小尺寸图片的宽和高。
IMAGES_MIN_WIDTH = 110  # 最小宽度
IMAGES_MIN_HEIGHT = 110  # 最小高度

ITEM_PIPELINES = {
   'steam_image.pipelines.SteamImagePipeline': 300,
   'steam_image.pipelines.SteamDownLoadPipeline': 100,   # 开启下载下载中间件
}

2.spider

# -*- coding: utf-8 -*-
import scrapy, pymysql, copy


class ImagesSpider(scrapy.Spider):
    name = 'images'
    allowed_domains = ['.com']
    start_urls = ['https://www.baidu.com/']

    def parse(self, response):
        db = pymysql.connect(host='localhost', port=3306, database='game', user='root', password='root',
                             charset='utf8', autocommit=True)
        cursor = db.cursor()
        cursor.execute(
            'SELECT id, appid, steam_image, steam_image_600_338 from steam_game_image WHERE id<5')  #  获取图片url
        for appid in cursor.fetchall():
            for i in range(2, 4):
                item = {}
                item['id'] = appid[0]
                item['appid'] = appid[1]
                item['image_url'] = appid[i]   # 下载图片的url    前面要自己获取到 图片的url   可以自己爬
                item['img_name'] = str(item['appid']) + '_' + appid[i].split('/')[-1].split('?')[0]   # 后面图片要命名的名称
                yield item

3.pipelines.py

# -*- coding: utf-8 -*-
from scrapy.pipelines.images import ImagesPipeline  # 导入图片类
import scrapy, os
from steam_image.settings import IMAGES_STORE as IMGS  # 导入图片保存路径


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


# 下载图片管道
class SteamDownLoadPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        yield scrapy.Request(item['image_url'])  # 下载图片

    def item_completed(self, results, item, info):
        print('******the results is********:', results)
        # results = [(True, {'url': 'http://img.ivsky.com/img/bizhi/pre/201101/10/harry_potter5-015.jpg', 'path': 'full/539c5914730497b094e5c98bfdfe19b65f5.jpg', 'checksum': '37d23ffb0ab983ac2da9a9d'})]
        # 真实结构为一个list [(DownLoad_success_or_failure),dict],字典中含有三个键:1、'url':图片路径 2、'path':图片下载后的保存路径 3、'checksum':校验码
        if results[0][0]:  # 可以判断图片下载是否成功   成功显示 Trur  失败显示False
            try:
                os.rename(IMGS + '\\' + results[0][1]['path'],
                          IMGS + '\\' + item['img_name'])  # 默认图片命名是嘻哈值  这里我们要改成自己的需要的图片名称  item['img_name] 是spider我们自己定义传过的
            except Exception as e:
                print('错误类型:{}'.format(e))  # 如果这个文件名称 我们前面的重命名回报错,这里我们要捕捉一下

    def close_spider(self, spider):
        # 完成后删除full目录  默认图片下载在你下载目录下回生成一个full文件,  你下载的图片默认回放在这个文件中
        os.removedirs(IMGS + '\\' + 'full')