python - 使用其他爬取信息的 scrapy 图像管道文件名

标签 python scrapy scrapy-pipeline

有没有办法用我们通过蜘蛛获得的其他信息(文本)来命名已爬行的图像? 例如,在本例中,我想要带有我在蜘蛛中获得的文章标题和文章发布日期的图像:

蜘蛛文件

# lines of code 

def parse(self, response):

    # lines of code 

    yield {
            'date':date,
            'title': article_title,
            'image_urls': clean_urls
    }

pipelines.py

from scrapy.pipelines.images import ImagesPipeline

class customImagesPipeline(ImagesPipeline):
    def file_path(self, request, response=None, info=None, *, item=None):
        return f"images/{request.url.split('/')[-1]}"

最佳答案

解决此问题的一种方法是覆盖 get_media_requests 方法,并在图像请求 meta 属性上设置图像名称,以便您可以在 file_path 方法。

如果您将一个图像 URL 作为字符串传递给 image_urls,则以下示例将起作用:

from scrapy.http import Request
from scrapy.pipelines.images import ImagesPipeline


class customImagesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        return Request(
            item["image_urls"],
            meta = {
                "image_name": f"{item['title']}_{item['date']}",
            }
        )

    def file_path(self, request, response=None, info=None) -> str:
        return f"images/{request.meta['image_name']}.jpg"

关于python - 使用其他爬取信息的 scrapy 图像管道文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72240650/

相关文章:

python - 现实生活过程的异步、多线程模拟

python - 类型错误 : Object of type 'bytes' is not JSON serializable

cookies - 使用 Scrapy 请求发送随机 cookie

Scrapy:如何通过 api 将项目发送到站点

python - Scrapy:如何在蜘蛛中使用项目以及如何将项目发送到管道?

python - 无法在 python 列表中将字符串转换为 int

python - 在python中打印出$和*+2字符之间的所有字符串

Python imaplib 登录失败

python - scrapy:CrawlSpider 中的 'exceptions.KeyError'

Scrapy:升级管道发送元素