Trouble renaming downloaded images in a customized manner through pipelines

こ雲淡風輕ζ 提交于 2019-12-02 18:39:52

问题


I've created a script using python's scrapy module to download and rename movie images from a torrent site and store them in a folder within scrapy project. When I run my script as it is, I find it downloading images in that folder folder errorlessly.

At this moment the script is renaming those images using a convenient portion from request.url through pipelines.py.

How can I rename those downloaded images through pipelines.py using their movie names from the variable movie defined within get_images() method?

spider contains:

from scrapy.crawler import CrawlerProcess
import scrapy, os

class yify_sp_spider(scrapy.Spider):
    name = "yify"
    start_urls = ["https://yts.am/browse-movies"]

    custom_settings = {
        'ITEM_PIPELINES': {'yify_spider.pipelines.YifySpiderPipeline': 1},
        'IMAGES_STORE': r"C:\Users\WCS\Desktop\yify_spider\yify_spider\spiders\Images",
    }

    def parse(self, response):
        for item in response.css(".browse-movie-wrap"):
            movie_name = ''.join(item.css(".browse-movie-title::text").get().split())
            img_link = item.css("img.img-responsive::attr(src)").get()
            yield scrapy.Request(img_link, callback=self.get_images,meta={'movie':movie_name})

    def get_images(self, response):
        movie = response.meta['movie']
        yield {
            "movie":movie,
            'image_urls': [response.url],
        }

if __name__ == "__main__":
    c = CrawlerProcess({
        'USER_AGENT': 'Mozilla/5.0',   
    })
    c.crawl(yify_sp_spider)
    c.start()

pipelines.py contains:

from scrapy.pipelines.images import ImagesPipeline

class YifySpiderPipeline(ImagesPipeline):

    def file_path(self, request, response=None, info=None):
        image_name = request.url.split('/')[-2]+".jpg"
        return image_name

One of such downloaded images should look like Obsession.jpg when the renaming is done.


回答1:


Override get_media_requests() and add the data you need to the request. Then grab that data from the request in file_path().

For example:

class YifySpiderPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        # Here we add the whole item, but you can add only a single field too.
        return [Request(x, meta={'item': item) for x in item.get(self.images_urls_field, [])]

    def file_path(self, request, response=None, info=None):
        item = request.meta.get('item')
        movie = item['movie']
        # Construct the filename.
        return image_name


来源:https://stackoverflow.com/questions/54773331/trouble-renaming-downloaded-images-in-a-customized-manner-through-pipelines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!