如何重命名图像scrapy的工作原理?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (69)

我尝试在items.py文件重命名,但是无法实现。请问该怎么做?

settings.py

SPIDER_MODULES = ['xxx.spiders']
NEWSPIDER_MODULE = 'xxx.spiders'
ITEM_PIPELINES = {'scrapy.pipelines.images.ImagesPipeline': 1}
IMAGES_STORE = '/home/magicnt/xxx/images'

items.py

class XxxItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    image_urls = scrapy.Field()
    #images = scrapy.Field()<---with that code work with default name images
    images = title<--- I try rename here, but not work

spider.py

from xxx.items import XxxItem
import scrapy
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem

class CoverSpider(scrapy.Spider):
    name = "pyimagesearch-cover-spider"
    start_urls = ['https://xxx.com.br/product']
    def parse(self, response):
        for bimb in response.css('#mod_imoveis_result'):
            imageURL = bimb.xpath('./div[@id="g-img-imo"]/div[@class="img_p_results"]/img/@src').extract_first()
            title = bimb.css('#titulo_imovel::text').extract_first()
            yield {
                'image_urls' : [response.urljoin(imageURL)],
                'title' : title
            }
        next_page = response.xpath('//a[contains(@class, "num_pages") and contains(@class, "pg_number_next")]/@href').extract_first()
        yield response.follow(next_page, self.parse)

我的目标是用项目标题重命名下载的图像。

提问于
用户回答回答于

一周前我对它进行了测试,它在我自己的spiders上起作用。

# This pipeline is designed for an item with multiple images
class ImagesWithNamesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        # values in field "image_name" must have suffix ".jpg"
        # you can only change "image_name" to your own image name filed "images"
        # however it should be a list
        for (image_url, image_name) in zip(item[self.IMAGES_URLS_FIELD], item["image_names"]):
            yield scrapy.Request(url=image_url, meta={"image_name": image_name})

    def file_path(self, request, response=None, info=None):
        image_name = request.meta["image_name"]
        return image_name

ImagePipeline如何工作的:

管道将执行image_downloaded->get_images->file_path(“->”指调用)

  • image_downloaded:保存get_images通过调用返回的图像persist_file
  • get_images:将图像转换为JPEG
  • file_path:返回图像的相对路径

我浏览了一下图像管道的源代码(https://github.com/scrapy/scrapy/blob/master/scrapy/pipelines/images.py),没有找到用于重命名图像的特殊字段。在scrapy上这样的方式重命名它:

def file_path(self, request, response=None, info=None):
    image_guid = hashlib.sha1(to_bytes(url)).hexdigest()  # change to request.url after deprecation
    return 'full/%s.jpg' % (image_guid)

只需要返回相对路径persist_file即可完成。

扫码关注云+社区

领取腾讯云代金券