class PicSpiderPipeline(ImagesPipeline): def get_media_requests(self, item, info): image_requests = super().get_media_requests(item,info) for img_req in image_requests: img_req.item = item return image_requests def file_path(self, request, response=None, info=None, *, item=None): old_path = super().file_path(request,response,info) title = request.item['title'] save_path = os.path.join(settings.IMAGES_STORE,title[0].replace('|','')) image_name = old_path.replace('full/','') return os.path.join(save_path,image_name) 此代码中怎样知道标题title含有特殊符号
时间: 2024-04-16 14:24:17 浏览: 128
在给`item`赋值的时候,可以使用`re.sub()`函数来替换特殊字符。以下是修改后的代码:
```python
import re
class PicSpiderPipeline(ImagesPipeline):
def get_media_requests(self, item, info):
image_requests = super().get_media_requests(item, info)
for img_req in image_requests:
img_req.item = item
return image_requests
def file_path(self, request, response=None, info=None, *, item=None):
old_path = super().file_path(request, response, info)
title = request.item['title']
# 使用re.sub()替换特殊字符
title = re.sub(r'[|]', '', title)
save_path = os.path.join(settings.IMAGES_STORE, title[0])
image_name = old_path.replace('full/', '')
return os.path.join(save_path, image_name)
```
在这个修改后的代码中,通过使用`re.sub()`函数,我们将标题中的`|`符号替换为空字符串,这样就可以确保标题中不再含有特殊字符。然后我们仍然使用替换后的标题作为保存路径的一部分。
阅读全文