![](/img/trans.png)
[英]How to insert a document with null value into mongodb using pymongo?
[英]Insert document in MongoDB using pymongo
我是第一次使用Python运行搜寻器。 我已经使搜寻器正常工作,现在我想使用pymongo将结果保存在MongoDB中,但是由于某些原因,我会收到此错误:“ NameError:未定义名称'city'。 如果我用引号将城市包裹起来,它可以按预期工作,但是我想按原样保存它。 任何人都做了类似的事情或知道解决方案是什么?
def gotHolidays(self, response):
cityName = response.meta['name']
feriado = []
facult = []
for selector in response.css("span.one"):
feriado.append(selector.css("::text").extract())
for selector in response.css("span.two"):
facult.append(selector.css("::text").extract())
city = {
'city': cityName,
'holidays':{
'facult': facult,
'feriado': feriado
}
}
print(json.dumps(city))
from pymongo import MongoClient
client = MongoClient()
client = MongoClient ('localhost', 27017)
db = client['myBank']
myCollection = db.myCollection
myCollection_data = {
'cities': city
}
result = myCollection.insert_one (myCollection_data)
缩进在您的代码片段中看起来是错误的。 from pymongo import ...
的行应与上一行的缩进级别相同:
print(json.dumps(city))
from pymongo import MongoClient
client = MongoClient()
对于python,缩进定义了范围。 python将非缩进代码解释为“函数结尾”。 因此,当您尝试访问“城市”变量时,该变量不再在范围内
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.