Python爬虫-Scrapy框架之下载文件和图片

  背景:Scrapy为下载Item中包含的文件(比如在爬取到产品时,同时也想保存对应的图片)提供了一个可重用的item pipelines,这些pipeline有些共同的方法和结构(我们称之为media pipeline),一般来说你会使用Files Pipeline或者Images Pipeline

1、为什么要选择使用Scrapy内置的下载文件的方法:

  • 1、避免重新下载最近已经下载过的文件;
  • 2、可以方便的指定文件存储的路径;
  • 3、可以将下载的图片转换成通用的格式,比如png或jpg;
  • 4、可以方便的生成缩略图;
  • 5、可以方便的检测图片的宽和高,确保他们满足最小限制;
  • 6、异步下载,效率非常高

2、下载文件的Files Pipeline

&emps; 当使用Files Pipeline下载文件的时候,按照以下步骤来完成:
&emps; 1、定义好一个item,然后在这个item中定义两个属性,分别为file_urls以及filesfile_urls是用来存储需要下载的图片的url链接, 需要给一个列表;
&emps; 2、当文件下载完成后,会把文件下载的相关信息存储到itemfiles属性中,比如下载路径、下载的url和文件的校验码等;
&emps; 3、在配置文件settings.py中配置FILES_STORE,这个配置是用来设置文件下载下来的路径;
&emps; 4、启动pipeline:在ITEM_PIPELINES中设置'scrapy.pipelines.files.FilesPipeline':1

3、下载图片的Images Pipeline

  当使用Images Pipeline下载图片的时候,按照以下步骤来完成:
&emps; 1、定义好一个item,然后在这个item中定义两个属性,分别为image_urls以及imagesimage_urls是用来存储需要下载的图片的url链接, 需要给一个列表;
&emps; 2、当文件下载完成后,会把文件下载的相关信息存储到itemimages属性中,比如下载路径、下载的url和文件的校验码等;
&emps; 3、在配置文件settings.py中配置IMAGES_STORE,这个配置是用来设置文件下载下来的路径;
&emps; 4、启动pipeline:在ITEM_PIPELINES中设置'scrapy.pipelines.images.ImagesPipeline':1

4、常规实现

  A)settings.py文件配置:

ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 1

DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.9 Safari/537.36',
}

ITEM_PIPELINES = {
   'autohome.pipelines.AutohomePipeline': 300,
}

  B)start.py文件如下:

from scrapy import cmdline
cmdline.execute("scrapy crawl bmw5".split())

  C)bmw5.py文件如下:

# -*- coding: utf-8 -*-
import scrapy
from autohome.items import AutohomeItem


class Bmw5Spider(scrapy.Spider):
    name = 'bmw5'
    allowed_domains = ['car.autohome.com.cn']
    start_urls = ['https://car.autohome.com.cn/pic/series/65.html#pvareaid=3454438']

    def parse(self, response):
        uiboxes = response.xpath("//div[@class='uibox']")[1:]
        for uibox in uiboxes:
            boxTitle = uibox.xpath(".//div[@class='uibox-title']/a/text()").get()
            urls = uibox.xpath(".//ul/li/a/img/@src").getall()
            urls = list(map(lambda url: response.urljoin(url), urls))
            item = AutohomeItem(boxTitle=boxTitle, urls=urls)
            yield item

  D)items.py文件如下:

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

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

import scrapy


class AutohomeItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    boxTitle = scrapy.Field()
    urls = scrapy.Field()

  E)pipelines.py文件如下:

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import os
from urllib import request

class AutohomePipeline:
    def __init__(self):
        self.path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "images")
        if not os.path.exists(self.path):
            os.mkdir(self.path)

    def process_item(self, item, spider):
        boxTitle = item['boxTitle']
        urls = item['urls']
        boxTitlePath = os.path.join(self.path, boxTitle)
        if not os.path.exists(boxTitlePath):
            os.mkdir(boxTitlePath)
        for url in urls:
            imageName = url.split("_")[-1]
            request.urlretrieve(url, os.path.join(boxTitlePath, imageName))
        return item

5、Scrapy实现

  A)settings.py文件配置:

ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 1

DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.9 Safari/537.36',
}

ITEM_PIPELINES = {
    # 'autohome.pipelines.AutohomePipeline': 300,
    'scrapy.pipelines.images.ImagesPipeline': 1,
}

# 图片下载的路径,供images pipelines使用
IMAGES_STORE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images')

  B)start.py文件如下:

from scrapy import cmdline
cmdline.execute("scrapy crawl bmw5".split())

  C)bmw5.py文件如下:

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

from autohome.items import AutohomeItem


class Bmw5Spider(scrapy.Spider):
    name = 'bmw5'
    allowed_domains = ['car.autohome.com.cn']
    start_urls = ['https://car.autohome.com.cn/pic/series/65.html#pvareaid=3454438']

    def parse(self, response):
        uiboxes = response.xpath("//div[@class='uibox']")[1:]
        for uibox in uiboxes:
            boxTitle = uibox.xpath(".//div[@class='uibox-title']/a/text()").get()
            urls = uibox.xpath(".//ul/li/a/img/@src").getall()
            urls = list(map(lambda url: response.urljoin(url), urls))
            item = AutohomeItem(boxTitle=boxTitle, image_urls=urls)
            yield item

  D)items.py文件如下:

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

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

import scrapy


class AutohomeItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    boxTitle = scrapy.Field()
    image_urls = scrapy.Field()
    images = scrapy.Field()

  E)pipelines.py文件如下:

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# import os
# from urllib import request


# class AutohomePipeline:
#     def __init__(self):
#         self.path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "images")
#         if not os.path.exists(self.path):
#             os.mkdir(self.path)
#
#     def process_item(self, item, spider):
#         boxTitle = item['boxTitle']
#         urls = item['imnage_urls']
#         boxTitlePath = os.path.join(self.path, boxTitle)
#         if not os.path.exists(boxTitlePath):
#             os.mkdir(boxTitlePath)
#         for url in urls:
#             imageName = url.split("_")[-1]
#             request.urlretrieve(url, os.path.join(boxTitlePath, imageName))
#         return item

6、Scrapy实现(优化改进)

  A)settings.py文件配置:

ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 1

DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.9 Safari/537.36',
}

ITEM_PIPELINES = {
    # 'autohome.pipelines.AutohomePipeline': 300,
    # 'scrapy.pipelines.images.ImagesPipeline': 1,
    'autohome.pipelines.BMWImagesPipeline': 1,
}

# 图片下载的路径,供images pipelines使用
IMAGES_STORE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images')

  B)start.py文件如下:

from scrapy import cmdline
cmdline.execute("scrapy crawl bmw5".split())

  C)bmw5.py文件如下:

# -*- coding: utf-8 -*-
import scrapy
from autohome.items import AutohomeItem


class Bmw5Spider(scrapy.Spider):
    name = 'bmw5'
    allowed_domains = ['car.autohome.com.cn']
    start_urls = ['https://car.autohome.com.cn/pic/series/65.html#pvareaid=3454438']

    def parse(self, response):
        uiboxes = response.xpath("//div[@class='uibox']")[1:]
        for uibox in uiboxes:
            boxTitle = uibox.xpath(".//div[@class='uibox-title']/a/text()").get()
            urls = uibox.xpath(".//ul/li/a/img/@src").getall()
            urls = list(map(lambda url: response.urljoin(url), urls))
            item = AutohomeItem(boxTitle=boxTitle, image_urls=urls)
            yield item

  D)items.py文件如下:

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

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

import scrapy


class AutohomeItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    boxTitle = scrapy.Field()
    image_urls = scrapy.Field()
    images = scrapy.Field()

  E)pipelines.py文件如下:

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import os
# from urllib import request
from scrapy.pipelines.images import ImagesPipeline
from autohome import settings


# class AutohomePipeline:
#     def __init__(self):
#         self.path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "images")
#         if not os.path.exists(self.path):
#             os.mkdir(self.path)
#
#     def process_item(self, item, spider):
#         boxTitle = item['boxTitle']
#         urls = item['imnage_urls']
#         boxTitlePath = os.path.join(self.path, boxTitle)
#         if not os.path.exists(boxTitlePath):
#             os.mkdir(boxTitlePath)
#         for url in urls:
#             imageName = url.split("_")[-1]
#             request.urlretrieve(url, os.path.join(boxTitlePath, imageName))
#         return item


class BMWImagesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        # 这个方法是在发送下载请求之前调用,其实这个方法本身就是去发送下载请求的
        request_objs = super(BMWImagesPipeline, self).get_media_requests(item, info)
        for request_obj in request_objs:
            request_obj.item = item
        return request_objs

    def file_path(self, request, response=None, info=None):
        # 这个方法是在图片将要被存储的时候调用,来获取这个图片存储的路径
        path = super(BMWImagesPipeline, self).file_path(request, response, info)
        boxTitle = request.item.get('boxTitle')
        imagesStore = settings.IMAGES_STORE
        boxTitlePath = os.path.join(imagesStore, boxTitle)
        if not os.path.exists(boxTitlePath):
            os.mkdir(boxTitlePath)
        imageName = path.replace("full/", "")
        imagePath = os.path.join(boxTitlePath, imageName)
        return imagePath

7、Scrapy实现(下载高清图片)

  A)settings.py文件配置:

ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 1

DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.9 Safari/537.36',
}

ITEM_PIPELINES = {
    # 'autohome.pipelines.AutohomePipeline': 300,
    # 'scrapy.pipelines.images.ImagesPipeline': 1,
    'autohome.pipelines.BMWImagesPipeline': 1,
}

# 图片下载的路径,供images pipelines使用
IMAGES_STORE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images')

  B)start.py文件如下:

from scrapy import cmdline
cmdline.execute("scrapy crawl bmw5".split())

  C)bmw5.py文件如下:

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

# import scrapy
from autohome.items import AutohomeItem
from scrapy.spiders import CrawlSpider
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor


# class Bmw5Spider(scrapy.Spider):
#     name = 'bmw5'
#     allowed_domains = ['car.autohome.com.cn']
#     start_urls = ['https://car.autohome.com.cn/pic/series/65.html']
#
#     def parse(self, response):
#         uiboxes = response.xpath("//div[@class='uibox']")[1:]
#         for uibox in uiboxes:
#             boxTitle = uibox.xpath(".//div[@class='uibox-title']/a/text()").get()
#             urls = uibox.xpath(".//ul/li/a/img/@src").getall()
#             urls = list(map(lambda url: response.urljoin(url), urls))
#             item = AutohomeItem(boxTitle=boxTitle, image_urls=urls)
#             yield item


class Bmw5Spider(CrawlSpider):
    name = 'bmw5'
    allowed_domains = ['car.autohome.com.cn']
    start_urls = ['https://car.autohome.com.cn/pic/series/65.html']
    rules = (Rule
             (LinkExtractor(allow=r'https://car.autohome.com.cn/pic/series/65.+'),
              callback="parse",
              follow=True
              ),
             )

    def parse(self, response):
        uiboxes = response.xpath("//div[@class='uibox']")[1:]
        for uibox in uiboxes:
            boxTitle = uibox.xpath(".//div[@class='uibox-title']/a/text()").get()
            imageSrcs = uibox.xpath(".//ul/li/a/img/@src").getall()
            imageSrcs = list(map(lambda imageSrc: imageSrc.replace("c42_", ""), imageSrcs))
            imageSrcs = list(map(lambda imageSrc: imageSrc.replace("240x180_0", "1024x0_1"), imageSrcs))
            imageSrcs = list(map(lambda imageSrc: response.urljoin(imageSrc), imageSrcs))
            item = AutohomeItem(boxTitle=boxTitle, image_urls=imageSrcs)
            yield item

  D)items.py文件如下:

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

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

import scrapy


class AutohomeItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    boxTitle = scrapy.Field()
    image_urls = scrapy.Field()
    images = scrapy.Field()

  E)pipelines.py文件如下:

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import os
# from urllib import request
from scrapy.pipelines.images import ImagesPipeline
from autohome import settings


# class AutohomePipeline:
#     def __init__(self):
#         self.path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "images")
#         if not os.path.exists(self.path):
#             os.mkdir(self.path)
#
#     def process_item(self, item, spider):
#         boxTitle = item['boxTitle']
#         urls = item['imnage_urls']
#         boxTitlePath = os.path.join(self.path, boxTitle)
#         if not os.path.exists(boxTitlePath):
#             os.mkdir(boxTitlePath)
#         for url in urls:
#             imageName = url.split("_")[-1]
#             request.urlretrieve(url, os.path.join(boxTitlePath, imageName))
#         return item


class BMWImagesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        # 这个方法是在发送下载请求之前调用,其实这个方法本身就是去发送下载请求的
        request_objs = super(BMWImagesPipeline, self).get_media_requests(item, info)
        for request_obj in request_objs:
            request_obj.item = item
        return request_objs

    def file_path(self, request, response=None, info=None):
        # 这个方法是在图片将要被存储的时候调用,来获取这个图片存储的路径
        path = super(BMWImagesPipeline, self).file_path(request, response, info)
        boxTitle = request.item.get('boxTitle')
        imagesStore = settings.IMAGES_STORE
        boxTitlePath = os.path.join(imagesStore, boxTitle)
        if not os.path.exists(boxTitlePath):
            os.mkdir(boxTitlePath)
        imageName = path.replace("full/", "")
        imagePath = os.path.join(boxTitlePath, imageName)
        return imagePath
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343