Python + Scrapy重命名下载的图像

时间:2017-06-11 07:57:53

标签: python web-scraping scrapy scrapy-spider scrapy-pipeline

重要说明:stackoverflow上目前提供的所有答案均适用于以前版本的Scrapy,不适用于最新版本的scrapy 1.4

scrapy和python的新手,我试图刮掉一些页面并下载图像。正在下载 图像 ,但它们仍然具有原始SHA-1名称作为文件名。 我无法弄清楚如何重命名文件,它们实际上都有SHA-1文件名

尝试将它们重命名为“test”,当我运行scrapy crawl rambopics以及url的数据时,我确实在输出中出现了“test”。但文件不会在目标文件夹中重命名。以下是输出示例:

> 2017-06-11 00:27:06 [scrapy.core.scraper] DEBUG: Scraped from <200
> http://www.theurl.com/> {'image_urls':
> ['https://www.theurl.com/-a4Bj-ENjHOY/VyE1mGuJyUI/EAAAAAAAHMk/mw1_H-mEAc0QQEwp9UkTipxNCVR-xdbcgCLcB/s1600/Image%2B%25286%2525.jpg'],
> 'image_name': ['test'], 'title': ['test'], 'filename': ['test'],
> 'images': [{'url':
> 'https://www.theurl.com/-a4Bj-ENjHOY/VyE1mGuJyUI/EAAAAAAAHMk/mw1_H-mEAc0QQEwp9UkTipxNCVR-xdbcgCLcB/s1600/Image%2B%25286%2525.jpg',
> 'path': 'full/fcbec9bf940b48c248213abe5cd2fa1c690cb879.jpg',
> 'checksum': '7be30d939a7250cc318e6ef18a6b0981'}]}

到目前为止,我已尝试在stackoverflow上发布了许多不同的解决方案,对于2017年最新版scrapy的问题,没有明确的答案,看起来这些命题可能几乎都已过时。我正在使用Scrapy 1.4和python 3.6。

scrapy.cfg

# Automatically created by: scrapy startproject
#
# For more information about the [deploy] section see:
# https://scrapyd.readthedocs.org/en/latest/deploy.html

[settings]
default = rambopics.settings

[deploy]
#url = http://localhost:6800/
project = rambopics

items.py 进口scrapy

class RambopicsItem(scrapy.Item):
    # defining items:
     image_urls = scrapy.Field()
     images = scrapy.Field()
     image_name = scrapy.Field()
     title = scrapy.Field()
    #pass -- dont realy understand what pass is for

settings.py

BOT_NAME = 'rambopics'

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


ROBOTSTXT_OBEY = True


ITEM_PIPELINES = {
   'scrapy.pipelines.images.ImagesPipeline': 1,
}

IMAGES_STORE = "W:/scraped/"

pipelines.py

import scrapy
from scrapy.pipelines.images import ImagesPipeline

class RambopicsPipeline(ImagesPipeline):


    def get_media_requests(self, item, info):

        img_url = item['img_url']
        meta = {
                  'filename': item['title'],
                   'title': item['image_name']
                }

        yield Request(url=img_url, meta=meta)

(蜘蛛)rambopics.py

from rambopics.items import RambopicsItem
from scrapy.selector import Selector
import scrapy


class RambopicsSpider(scrapy.Spider):
    name = 'rambopics'
    allowed_domains = ['theurl.com']
    start_urls = ['http://www.theurl.com/']

    def parse(self, response):

        for sel in response.xpath('/html'):
            #img_name = sel.xpath("//h3[contains(@class, 'entry-title')]/a/text()").extract()
            img_name = 'test'
            #img_title = sel.xpath("//h3[contains(@class, 'entry-title')]/a/text()").extract()
            img_title = 'test' 

        for elem in response.xpath("//div[contains(@class, 'entry-content')]"):
            img_url = elem.xpath("a/@href").extract_first()


            yield {
                   'image_urls': [img_url],
                   'image_name': [img_name],
                   'title': [img_title],
                   'filename': [img_name]
               }

注意,我不知道正确的元名称用于最终下载的文件名(我不确定它的文件名,图像名称或标题)。

1 个答案:

答案 0 :(得分:0)

使用 file_path 方法更改图片名称。

class SaveImagesPipeline(FilesPipeline):
    def get_media_requests(self, item, info):
        i = 1
        for image_url in item['image_urls']:
            filename = '{}_{}.jpg'.format(item['name_image'], i)
            yield scrapy.Request(image_url, meta={'filename': filename})
            i += 1
    return

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