scrapy 鲜花数据爬虫之【上】图片下载

本项目仅供学习之用

1 爬虫开发

利用scrapy工程编写爬取鲜花数据的爬虫,本次的目标是先下载相关的图片,要下载图片首先要获取到的就是图片的链接,爬虫的编写如下:

python 复制代码
class FlowerSpider(scrapy.Spider):
    name = 'flower'
    allowed_domains = ['huafensi.com']
    start_urls = [f"http://www.huafensi.com/huahui/page_{i}.html" for i in range(1, 63)]

    def parse(self, response):
        flower_items = response.css('div.part-cont3 dl')

        for flower in flower_items:
            title = flower.css('dt a::attr(title)').get()
            img_src = flower.css('dt a img::attr(src)').get()
            img_src = response.urljoin(img_src)
            detail_url = flower.css('dt a::attr(href)').get()
            detail_url = response.urljoin(detail_url)

            # 创建 FlowerItem 实例
            item = FlowerItem()
            item['title'] = title
            item['image_urls'] = [img_src]
            item['detail_url'] = detail_url

            return item

item部分之需要把上面用到的3个变量定义一下就行了,然后重点是管道部分,需要开发一个专门下载图片的管道

python 复制代码
class CustomImagesPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        for image_url in item['image_urls']:
            yield Request(image_url)

    def file_path(self, request, response=None, info=None, *, item=None):
        # 使用 item['title'] 生成文件名
        title = item['title'].replace(' ', '_').replace('/', '_')  # 替换空格和斜杠为下划线,避免路径问题
        filename = f'{title}.jpg'  # 假设所有图片格式为 jpg
        return filename

    def item_completed(self, results, item, info):
        image_paths = [x['path'] for ok, x in results if ok]
        if not image_paths:
            raise DropItem("Item contains no images")
        item['images'] = image_paths
        return item

这样图片会自动下载到img文件夹里去了,记得在settings.py里激活一下这个自定义的管道。

2 爬虫运行截图

3 爬取图片结果

总共爬取 1465 张图片,爬取结果如下

4 后续

下一篇来说如何爬取花卉的信息存入excel中。

相关推荐
喵手4 小时前
Python爬虫实战:实现 Playwright 的动态名言“瀑布流”采集器,采集名言内容、作者及出处等信息(附 JSON 格式数据导出)!
爬虫·python·爬虫实战·playwright·零基础python爬虫教学·构建动态名言瀑布流采集器·采集数据json导出
喵手4 小时前
Python爬虫实战:全国旅游景区名录智能采集系统 - 构建文旅大数据的基石(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·全国旅游景区名采集系统·文旅大数据·采集旅游景区sqlite存储
J_bean7 小时前
AI 智能爬虫实战
爬虫·ai·大模型
0思必得013 小时前
[Web自动化] Selenium无头模式
前端·爬虫·selenium·自动化·web自动化
Libraeking16 小时前
爬虫的“法”与“术”:在牢狱边缘疯狂试探?(附高阶环境配置指南)
爬虫
我是章汕呐17 小时前
拆解Libvio.link爬虫:从动态页面到反爬对抗的实战解析
爬虫·python
狗都不学爬虫_20 小时前
JS逆向 - 某住会同盾blackbox纯算分析
javascript·爬虫·python·网络爬虫
JNU freshman21 小时前
爬虫?先看网站的robots.txt
爬虫
深蓝电商API21 小时前
签名参数逆向:分析 sign 生成算法
爬虫·python
星川皆无恙21 小时前
豆瓣电影数据爬虫分析:基于 Python 的豆瓣电影数据可视化分析系统
大数据·爬虫·python·算法·机器学习·信息可视化·numpy