【问题标题】:Getting child-comments of a comment on Reddit with Praw in Python在 Python 中使用 Praw 获取 Reddit 评论的子评论
【发布时间】:2016-05-11 15:31:58
【问题描述】:

我正在使用 praw 从 reddit 线程中抓取信息。我可以使用r.get_submission(thread).comments 给我一个线程中的所有 cmets,但现在我想遍历所有这些 cmets 并获取子 cmets。

这是我所拥有的:

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。我正在使用尝试将评论作为提交的方法,因为它类似于我在研究https://www.reddit.com/r/redditdev/comments/1kxd1n/how_can_i_get_the_replies_to_a_comment_with_praw/时在这里看到的解决方案@

我的问题是:给定一个 praw comment 对象,我如何遍历所有作为回复的子 cmets?我想获取所有直接回复另一个评论对象的 cmets。

例如,在我的程序中的示例线程中,第一条评论是Not going out freshman year我想得到像Meh, I never went out at all in college.Your story sounds identical to mine这样的响应cmets

【问题讨论】:

    标签: python reddit praw


    【解决方案1】:

    它是一个简单的comment.replies,它返回与submission.comments相同类型的可迭代对象CommentMoreComments对象,后者用于同一级别的更多cmets。

    一些示例代码:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-17
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多