[英]PyMongo Collection Object Not Callable
我正在嘗試創建一個 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 文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.