Search code examples
scrapyscrapy-pipeline

How to download image using Scrapy?


I am newbie to scrapy. I am trying to download an image from here. I was following Official-Doc and this article.

My settings.py looks like:

BOT_NAME = 'shopclues'

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

ROBOTSTXT_OBEY = True

ITEM_PIPELINES = {
    'scrapy.contrib.pipeline.images.ImagesPipeline':1
}

IMAGES_STORE="home/pr.singh/Projects"


and items.py looks like:

import scrapy
from scrapy.item import Item

class ShopcluesItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass

class ImgData(Item):
    image_urls=scrapy.Field()
    images=scrapy.Field()

I think both these files are good. But I am unable to write correct spider for getting the image. I am able to grab the image URL but don't know how to store image using imagePipeline.
My spider looks like:

from shopclues.items import ImgData
import scrapy
import datetime


class DownloadFirstImg(scrapy.Spider):
    name="DownloadfirstImg"
    start_urls=[
    'http://www.shopclues.com/canon-powershot-sx410-is-2.html',
    ]

    def parse (self, response):
        url= response.css("body div.site-container div#container div.ml_containermain div.content-helper div.aside-site-content div.product form#product_form_83013851 div.product-gallery div#product_images_83013851_update div.slide a#det_img_link_83013851_25781870")

        yield scrapy.Request(url.xpath('@href').extract(),self.parse_page)

        def parse_page(self,response):
            imgURl=response.css("body div.site-container div#container div.ml_containermain div.content-helper div.aside-site-content div.product form#product_form_83013851 div.product-gallery div#product_images_83013851_update div.slide a#det_img_link_83013851_25781870::attr(href)").extract()

            yield {
            ImgData(image_urls=[imgURl])
            }

I have written the spider following this-article. But I am not getting anything. I run my spider as scrapy crawl DownloadfirstImg -o img5.json but I am not getting any json nor any image?
Any help on How to grab image if it's url is known. I have never worked with python also so things seem much complicated to me. Links to any good tutorial may help. TIA


Solution

  • I don't understand why you yield a request for an image you just need to save it on the item and the images pipeline will do the rest, this is all you need.

    def parse (self, response):
        url= response.css("body div.site-container div#container div.ml_containermain div.content-helper div.aside-site-content div.product form#product_form_83013851 div.product-gallery div#product_images_83013851_update div.slide a#det_img_link_83013851_25781870")
        yield ImgData(image_urls=[url.xpath('@href').extract_first()])