gpt4 book ai didi

python - PyMongo 集合对象不可调用

转载 作者:可可西里 更新时间:2023-11-01 10:00:31 26 4
gpt4 key购买 nike

我正在尝试创建一个 Reddit 抓取工具,它从 Reddit 主页获取前 100 页并将它们存储到 MongoDB 中。我不断收到错误消息:

TypeError: 'Collection' object is not callable. If you meant to call the 'insert_one' method on a 'Collection' object it is failing because no such method exists.

这是我的代码

import pymongo
import praw
import time


def main():
fpid = os.fork()
if fpid!=0:
# Running as daemon now. PID is fpid
sys.exit(0)

user_agent = ("Python Scraper by djames v0.1")
r = praw.Reddit(user_agent = user_agent) #Reddit API requires user agent

conn=pymongo.MongoClient()
db = conn.reddit
threads = db.threads


while 1==1: #Runs in an infinite loop, loop repeats every 30 seconds
frontpage_pull = r.get_front_page(limit=100) #get first 100 posts from reddit.com

for posts in frontpage_pull: #repeats for each of the 100 posts pulled
data = {}
data['title'] = posts.title
data['text'] = posts.selftext
threads.insert_one(data)
time.sleep(30)

if __name__ == "__main__":
main()

最佳答案

insert_one() 直到 3.0 版本才添加到 pymongo。如果您尝试在此之前的版本上调用它,您将得到您所看到的错误。

要检查你的 pymongo 版本,打开一个 python 解释器并输入:

import pymongo
pymongo.version

使用 pymongo 插入文档的传统方法就是使用 Collection.insert()。因此,在您的情况下,您可以将插入行更改为:

threads.insert(data)

有关详细信息,请参阅 pymongo 2.8 documentation

关于python - PyMongo 集合对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com