This topic created in 3119 days ago, the information mentioned may be changed or developed.
pipelines.py 中的关键代码为:
if db.mycollection.find({"ip":item["ip"]}):
print "{} has already existed.".format(item["ip"])
print db.mycollection.find()
else:
db.mycollection.insert_one(data)
print db.mycollection.count({})
执行的结果总是:
120.25.164.134 has already existed.
<pymongo.cursor.Cursor object at 0x0000000005B330F0>
……
提示我抓取到的每一条数据都是存在的,我的 mycollection 聚集中最开始是空的,为什么会出现这种情况呢?
14 replies • 2017-12-06 09:03:17 +08:00
 |
|
2
tosexxx Dec 3, 2017
大佬都在度假,没空 8 小时之外看 v 站
|
 |
|
3
SO647898 Dec 3, 2017 via Android
大佬都在度假,没空 8 小时之外看 v 站
|
 |
|
4
kenzh Dec 3, 2017 1
看了下文档,find()总是返回的是 Cursor, 猜测应该用 db.mycollection.find({"ip":item["ip"]}).count() 吧。
|
 |
|
5
golmic Dec 3, 2017 via Android
用 upsert
|
 |
|
7
brickyang Dec 3, 2017 via iPhone 1
.find() 返回的是 cursor,用 find().toArray() 返回的是查找结果的数组,如果不存在就是个空数组。
你也可以试试 .findOneAndUpdate() 并设置 upsert: true,这样如果找到记录则更新(更新内容为空),找不到则新建一条记录。
|
 |
|
8
fds Dec 3, 2017 1
返回的是 cursor,肯定为 True 呀,你得调用.next()才可能获得一个空结果吧。 另外,这种约束条件一般是这样实现:在 ip 上建立一个 unique 的索引,然后每次都直接插入;如果已有,则会报错 duplicate,忽略即可。你这种 ifelse 不是“原子”操作,如果有多个进程同时工作,可能插入多条相同 ip 的。
|
 |
|
10
lihongjie0209 Dec 3, 2017 1
动态语言就是有这个问题 如果你需要集合为空: 那么使用 if collection.isEmpty 或者是 if collection.size() == 0
如果你需要集合为 null/none: 那么使用 if collection== null/none
这样写代码的时候意图清楚, 看代码的人也轻松.
|
 |
|
14
toono Dec 6, 2017
find 方法返回的都是集合对象。
下面我的实际代码,是需要先把查询回来的结果对象使用 count 方法去查看具体数量
def process_item(self, item, spider): result = self.db[self.mongo_collection].find({'source_url': item['source_url']}) if result.count() != 0: raise DropItem("Duplicate item found: %s" % item) else: return item
|