4

I have following question: I need to save image to mongodb during web scraping. I have an image link. I tried this:

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
....

The code of Waralbum item:

from scrapy.item import Item, Field

class WaralbumPost(Item):
    images_binary = Field()

But this cause error when it saves to mongo: bson.errors.InvalidStringData: strings in documents must be valid UTF-8: '\xff\.....

What is better way to do this? Does converting of raw image data will solve this problem? Maybe, scrapy has a pretty way for saving images? Thank for your answers

SOLUTION: I deleted this lines: images_binaries.append(open(self.album_path + '/' + photo_file, 'r').read()) post['images_binary'] = images_binaries In my WaralbumPost I also save image url. Than, in pipelines.py I get this url and save image in mongo. the code of 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

Hope, this will be helpful for someone

Oleksandr H
  • 2,965
  • 10
  • 40
  • 58

1 Answers1

3

use 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();
Community
  • 1
  • 1
johntellsall
  • 14,394
  • 4
  • 46
  • 40