您遇到的问题,我相信是由于转义字符在Python插入到MongoDB的前没有充分转化为UTF-8格式。
我还没有检查MongoDB更改日志,但如果我没有记错,应该支持v.2.2 +完整unicode。
无论如何,你有两种方法,升级到更新版本的mongoDB 2.6,或修改/覆盖你的scrapy-mongodb
脚本。要改变scrapy_mongodb.py
,看看这些线,ķ插入的MongoDB之前没有转化为UTF-8:
# ... previous code ...
key = {}
if isinstance(self.config['unique_key'], list):
for k in dict(self.config['unique_key']).keys():
key[k] = item[k]
else:
key[self.config['unique_key']] = item[self.config['unique_key']]
self.collection.update(key, item, upsert=True)
# ... and the rest ...
为了解决这个问题,你可以process_item
函数中添加这几行:
# ... previous code ...
def process_item(self, item, spider):
""" Process the item and add it to MongoDB
:type item: Item object
:param item: The item to put into MongoDB
:type spider: BaseSpider object
:param spider: The spider running the queries
:returns: Item object
"""
item = dict(self._get_serialized_fields(item))
# add a recursive function to convert all unicode to utf-8 format
# take this snippet from this [SO answer](http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python)
def byteify(input):
if isinstance(input, dict):
return {byteify(key):byteify(value) for key,value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
# if above utf-8 conversion still not working, replace them completely
# return input.encode('ASCII', 'ignore')
else:
return input
# finally replace the item with this function
item = byteify(item)
# ... rest of the code ... #
如果这仍然不起作用,建议将您的mongodb升级到更新的版本。
希望这会有所帮助。
我试图插入其中一个文件,它对我来说没有任何错误,你使用的是哪个版本的mongodb,以及如何在db上插入文件? –
我正在使用版本2.4.6。这些示例不是我想要插入的文档,而是嵌套在文档中的对象。我要上传整个文档。 – ranisalt
这里是:https://gist.github.com/ranisalt/d7320d6993664e87b7c0这是一个要插入的整个文档 – ranisalt