目录
1.一般方法存入MongoDB
2.定义函数存入MongoDB
3.在scrapy中存入MongoDB
4.从数据库中取数据
正文:
1.一般方法存入MongoDB
import pymongo
from pymongo.collection import Collection #注意英文拼写
client= pymongo.MongoClient("localhost")
db= client['xxx'] #xxx为数据库名
id_Collection= Collection(db,'xxx') #xxx为表名
id_Collection.insert("{xxx}") #xxx为字典
2.定义函数存入MongoDB
import pymongo
def save_to_mongo(self,result):
client= pymongo.MongoClient("xxx") #联接客户端,本地写localhost,
db= client["xxx"] #数据库名称,按自己需求写一个
db['xxx'].Insert(result) #xxx为表名,result为要存的数据
3.在scrapy中存入MongoDB
#首先在setting中最下面加
mongo_host= "127.0.0.1"
mongo_port= 27017
mongo_db_name= "xxx"#xxx为数据库名称
mongo_db_collection= "xxx" #xxx为表名称
#然后在pipelines.py中
import pymongo
from xxx.settingsimport mongo_port
class xxxPipeline(object):
def __init__(self):
host= mongo_host
port= mongo_port
dbname= mongo_db_name
sheetname= mongo_db_collection
client= pymongo.MongoClient(host=host,port=port)
mydb= client[dbname]
self.post= mydb[sheetname]
def process_item(self,item,spider):
data= dict(item)
self.post.insert(data)
return item
4.从mongodb数据库中取数据
import pymongo
from pymongo.collectionimport Collection
client= pymongo.MongoClient("localhost:27017")
db= client['xxx']#xxx为数据库名
id_collection= Collection(db,'xxx') #xxx为表名
task_id_collection.find_one_and_delete({})#查找一个并删除掉