【问题标题】:Unable to rename downloaded images through pipelines without the usage of item.py在不使用 item.py 的情况下无法通过管道重命名下载的图像
【发布时间】:2019-02-17 20:37:53
【问题描述】:

我使用 python 的 scrapy 模块创建了一个脚本,用于从 torrent 站点的多个页面下载和重命名电影图像,并将它们存储在桌面文件夹中。当它是关于下载这些图像并将其存储在桌面文件夹中时,我的脚本是相同的,没有错误。但是,我现在正在努力做的是即时重命名这些文件。由于我没有使用item.py文件,我也不想使用,我几乎不明白pipelines.py文件的逻辑是如何处理重命名过程的。

我的蜘蛛 (It downloads the images flawlessly):

from scrapy.crawler import CrawlerProcess
import scrapy, os

class YifySpider(scrapy.Spider):
    name = "yify"

    allowed_domains = ["www.yify-torrent.org"]
    start_urls = ["https://www.yify-torrent.org/search/1080p/p-{}/".format(page) for page in range(1,5)]

    custom_settings = {
        'ITEM_PIPELINES': {'scrapy.pipelines.images.ImagesPipeline': 1},
        'IMAGES_STORE': r"C:\Users\WCS\Desktop\Images",
    }

    def parse(self, response):
        for link in response.css("article.img-item .poster-thumb::attr(src)").extract():
            img_link = response.urljoin(link)
            yield scrapy.Request(img_link, callback=self.get_images)

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

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

pipelines.py 包含:(the following lines are the placeholders to let you know I at least tried):

from scrapy.http import Request

class YifyPipeline(object):

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

    def get_media_requests(self, item, info):
        yield Request(item['image_urls'][0], meta=item)

如何在不使用item.py 的情况下通过pipelines.py 重命名图像?

【问题讨论】:

  • 我不明白 item.py 与它有什么关系。你会如何使用它?

标签: python python-3.x web-scraping scrapy scrapy-spider


【解决方案1】:

你需要继承原来的ImagesPipeline

from scrapy.pipelines.images import ImagesPipeline

class YifyPipeline(ImagesPipeline):

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

然后在你的设置中引用它:

custom_settings = {
    'ITEM_PIPELINES': {'my_project.pipelines.YifyPipeline': 1},
}

但请注意,当不同的文件具有相同的名称时,简单的“使用确切的文件名”的想法会导致问题,除非您在文件名中添加唯一的文件夹结构或附加组件。这是默认使用基于校验和的文件名的原因之一。请参阅原始的file_path,以防您想包含一些原始逻辑来防止这种情况发生。

【讨论】:

  • 最后,我发现它工作正常。您的解决方案完美无缺,但我遇到错误只是因为我使用CrawlerProcess 运行我的脚本。所以,为了让它正常工作,我需要在我的蜘蛛上使用这条线import sys; sys.path.append(r'C:\Users\WCS\Desktop\yify_spider'),它导致scrapy.cfg。但是,当使用CrawlerProcess 运行脚本时,您是否知道除了这个奇怪的导入之外的其他选择?谢谢。
  • @robots.txt 我不确定为什么首先需要这样做。您的文件结构或运行脚本的位置可能有些奇怪。
  • 您可能想查看this post 以提供任何解决方案@malberts。提前致谢。
猜你喜欢
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 2021-07-15
相关资源
最近更新 更多