如何将图像保存到具有图像URL的mongodb?

时间:2014-08-15 20:57:50

标签: python mongodb scrapy

我有以下问题:我需要在网络抓取期间将图像保存到mongodb。我有一个图像链接。我试过这个:

images_binaries = [] # this will store all images data before saving it to mongodb
# save as file on hard disc
urllib.urlretrieve(url, self.album_path + '/' + photo_file_name)
images_binaries.append(open(self.album_path + '/' + photo_file, 'r').read())
....
# after that I append this array of images raw data to Item
post = WaralbumPost()
post['images_binary'] = images_binaries
....

Waralbum项目代码:

from scrapy.item import Item, Field

class WaralbumPost(Item):
    images_binary = Field()

但是当它保存到mongo时会导致错误:bson.errors.InvalidStringData: strings in documents must be valid UTF-8: '\xff\.....

有什么更好的方法呢?转换原始图像数据会解决这个问题吗?也许,scrapy有一个很好的方法来保存图像? 谢谢你的回答

解: 我删除了这一行:     images_binaries.append(open(self.album_path +' /' + photo_file,' r')。read())     发布[' images_binary'] = images_binaries 在我的WaralbumPost中,我还保存了图片网址。比,在pipelines.py我得到这个网址并将图像保存在mongo中。 pipelines.py的代码:

class WarAlbum(object):
def __init__(self):
    connection = pymongo.Connection(settings['MONGODB_SERVER'], settings['MONGODB_PORT'])
    db = connection[settings['MONGODB_DB']]
    self.collection = db[settings['MONGODB_COLLECTION']]
    self.grid_fs = gridfs.GridFS(getattr(connection, settings['MONGODB_DB']))

def process_item(self, item, spider):
    links = item['img_links']
    ids = []
    for i, link in enumerate(links):
        mime_type = mimetypes.guess_type(link)[0]
        request = requests.get(link, stream=True)
        _id = self.grid_fs.put(request.raw, contentType=mime_type, filename=item['local_images'][i])
        ids.append(_id)
    item['data_chunk_id'] = ids
    self.collection.insert(dict(item))
    log.msg("Item wrote to MongoDB database %s/%s" %
            (settings['MONGODB_DB'], settings['MONGODB_COLLECTION']),
            level=log.DEBUG, spider=spider)
    return item

希望,这会对某人有所帮助

1 个答案:

答案 0 :(得分:2)

使用GridFS。 Example:

String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();