2016-05-01 6 views
0

私はredditスレッドから情報をスクラップするためにprawを使用しています。私はr.get_submission(thread).commentsを使ってスレッド内のすべてのコメントを私に渡すことができますが、今ではそれらのコメントをすべて繰り返して子コメントを得たいと思っています。ここでPythonでPrawを使ってRedditのコメントの子コメントを取得する

は、私が持っているものです。

r = praw.Reddit(user_agent="archiver v 1.0") 
thread = "https://www.reddit.com/r/AskReddit/comments/4h4o7s/what_do_you_regret_doing_at_university/" 
r.login(settings['username'], settings['password'], disable_warning=True) 
submission = r.get_submission(thread) 

for comment in submission.comments: 
    #this works, prints out the comments text 
    print(comment.body) 

    #now i want to get the child comments that are replied to this comment 
    commentSubmission = r.get_submission(comment.permalink) 
    #ideally comments[0] should show me first reply, comments[1] the second. etc 
    print(commentSubmission.comments[1]) 

これはIndexError: list index out of rangeをスローします。 praw commentオブジェクトを考えると、どのようにすることができます私はループを介してすべて:私はhttps://www.reddit.com/r/redditdev/comments/1kxd1n/how_can_i_get_the_replies_to_a_comment_with_praw/

私の質問ですが研究していたとき、それは私がここで見たソリューションに似だから、私は提出などのコメントを取得しようとする方法を使用しています子コメントは返信ですか?直接の返信であるすべてのコメントを別のコメントオブジェクトに取得したい。例えば、私のプログラムの例のスレッドで、最初のコメントはNot going out freshman year私はそれはcomment.replies同様に簡単ですMeh, I never went out at all in college.Your story sounds identical to mine

答えて

2

のような応答のコメントを取得したい、それはのように反復可能なのと同じようなものを返している

submission.commentsCommentMoreCommentsオブジェクトです。後者は、より多くのコメントを同じレベルで表示します。

いくつかのサンプルコード:

submission = r.get_submission(thread) 
process_comments(submission.comments) 

def process_comments(objects): 
    for object in objects: 
     if type(object).__name__ == "Comment": 
      process_comments(object.replies) # Get replies of comment 

      # Do stuff with comment (object) 

     elif type(object).__name__ == "MoreComments": 
      process_comments(object.comments()) # Get more comments at same level 
関連する問題