scrapy 如果有相同的图片就替换
时间: 2024-02-03 12:11:56 浏览: 24
在 Scrapy 中,如果想要替换相同的图片,可以使用 Item Pipeline。具体步骤如下:
1. 在 item.py 文件中定义一个新的字段,用于保存图片的 URL。
```python
import scrapy
class MyItem(scrapy.Item):
# 其他字段...
image_urls = scrapy.Field()
images = scrapy.Field()
```
2. 修改 settings.py 文件,启用下载图片的 Pipeline。
```python
ITEM_PIPELINES = {
'scrapy.pipelines.images.ImagesPipeline': 1,
}
```
3. 在 Pipeline 中实现替换图片的逻辑。可以继承 ImagesPipeline 并重写 item_completed 方法。
```python
from scrapy.pipelines.images import ImagesPipeline
class MyImagesPipeline(ImagesPipeline):
def item_completed(self, results, item, info):
# 获取下载成功的图片路径
image_paths = [x['path'] for ok, x in results if ok]
# 如果有下载成功的图片
if image_paths:
# 替换 item 中的 image_urls 和 images 字段
item['image_urls'] = [self.storage.url(path) for path in image_paths]
item['images'] = [{'url': self.storage.url(path), 'path': path} for path in image_paths]
return item
```
4. 修改 settings.py 文件,指定自定义的 Pipeline。
```python
ITEM_PIPELINES = {
'myproject.pipelines.MyImagesPipeline': 1,
}
```
这样 Scrapy 在下载图片时,如果发现已经存在相同的图片,则会直接使用已有的图片,而不会重复下载。当然,如果你想删除旧的图片,也可以在 item_completed 方法中实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
[talkid:138031390]2014年4月20日 06:55:45 , 2323234 向 342114 发送 我们已经是好友了,开始聊天吧! [talkid:138031381]2014年3月14日 02:25:45 , 2323234 向 2323234 发送 我们已经是好友了,开始聊天吧! [talkid:138031382]2014年4月20日 04:45:45 , 2323234 向 545321 发送 音频 :[音频 [talkid:138031383]2014年4月20日 04:55:45 , 2323234 向 345432 发送 图片 :[图片 [talkid:138031384]2014年4月20日 05:55:45 , 2323234 向 323455 发送 我们已经是好友了,开始聊天吧!使用爬虫爬取
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)