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中。

相关推荐
Smartdaili China14 分钟前
如何抓取维基百科. 完整初学者教程
爬虫·指南·抓取·wikipedia·抓取api·如何·百科
AI云原生1 小时前
如何解决 pip install 代理报错 SOCKS5 握手失败 ReadTimeoutError 问题
网络·爬虫·python·网络协议·tcp/ip·scikit-learn·pip
java1234_小锋1 天前
[免费]基于Python的天气预报(天气预测分析)(Django+sklearn机器学习+selenium爬虫)可视化系统【论文+源码+SQL脚本】
爬虫·python·selenium·天气预报·天气预测
3824278271 天前
python3网络爬虫开发实战 第2版:使用aiohttp
开发语言·爬虫·python
APIshop1 天前
API 接口文档测试:从“能跑”到“敢上线”的完整闭环
爬虫·python
盼哥PyAI实验室1 天前
[特殊字符]️ 实战爬虫:Python 抓取【采购公告】接口数据(含踩坑解析)
开发语言·爬虫·python
小白学大数据1 天前
Python 网络爬虫:Scrapy 解析汽车之家报价与评测
开发语言·爬虫·python·scrapy
weixin_446260851 天前
[特殊字符] MediaCrawler - 自媒体平台爬虫 [特殊字符]️
爬虫·媒体
傻啦嘿哟1 天前
用Kubernetes管理大规模爬虫节点:从单机到云原生的进化之路
爬虫·云原生·kubernetes
Elaine3362 天前
实战教学:使用 Scrapy 爬取 CSDN 文章与用户头像
python·scrapy·网络爬虫