【问题标题】:In praw, I'm trying to print the comment body, but what if I encounter an empty comment?在 praw 中,我正在尝试打印评论正文,但如果遇到空评论怎么办?
【发布时间】:2026-01-04 22:50:02
【问题描述】:

我正在尝试打印 subreddit 顶部帖子中的所有 cmets,以便我的机器人可以分析它们。我在当天早些时候运行它,但我现在尝试运行它,但遇到了一个错误。

这是我的代码:

r = praw.Reddit('Comment crawler v1.0 by /u/...')
r.login('username', 'password')
subreddit=r.get_subreddit('subreddit')
post_limit = 25
subreddit_posts = subreddit.get_hot(limit=post_limit)
subids = set()
for submission in subreddit_posts:
    subids.add(submission.id)
subid = list(subids)

i=0
while i < post_limit:
    submission = r.get_submission(submission_id=subid[i])
    flat_comments = praw.helpers.flatten_tree(submission.comments)
    with open('alreadydone.txt', 'r') as f:
        already_done = [line.strip() for line in f]
    f.close()
    for comment in flat_comments:
        if "Cricketbot, give me Australian news" in **comment.body** and comment.id not in already_done:
            info = feedparser.parse(Australia) #Australia gives a link to an RSS feed.

加星标的部分是我遇到问题的地方。我正在尝试查看写有“Cricketbot,给我澳大利亚新闻”的 cmets。不幸的是,如果评论的正文不存在,即评论为空,代码会返回一个属性错误并说评论没有属性“body”。

如何解决这个问题?

【问题讨论】:

    标签: python reddit


    【解决方案1】:

    添加堆栈跟踪通常会有所帮助,这样人们就可以看到实际的错误。但是,作为 PRAW 维护者,我知道错误类似于 MoreComments type has no attribute body

    有三种简单的方法可以解决您的问题。第一种是简单地将if "Cricketbot" 语句包装在try/except 中并忽略属性错误。

    try:
        if "Cricketbot..."
            ...
    except AttributeError:
        pass
    

    不过,这并不是非常令人兴奋。第二种方法是确保您实际使用的是具有body 属性的对象,这可以通过两种方式完成:

    首先是显式检查属性是否存在:

    for comment in flat_comments:
        if not hasattr(comment, 'body'):
            continue
        ...
    

    第二个是验证您实际上是在使用Comment 对象而不是MoreComments 对象:

    for comment in flat_comments:
        if not isinstance(comment, praw.objects.Comment):
            continue
        ...
    

    但是,在运行上述任何解决方案时,您实际上并未处理提交中的所有 cmets,因为您缺少隐藏在 MoreComments 对象 [ref] 后面的任何内容。要将MoreComments 对象替换为一些(全部替换可能非常低效)cmets 需要在展平树之前使用replace_more_comments 函数:

    submission = r.get_submission(submission_id=subid[i])
    submission.replace_more_comments(limit=16, threshold=10)
    flat_comments = praw.helpers.flatten_tree(submission.comments)
    

    设置limit=16threshold=10 表示不超过16 个额外请求,并且只发出至少会导致10 个额外cmets 的请求。您可以根据需要使用这些值,但请注意,每次替换都需要一个额外的请求(2 秒),有些只产生一条评论。

    希望对你有帮助。

    【讨论】:

    • 非常感谢!也很抱歉,确实是AttributeError: '&lt;class 'praw.objects.MoreComments'&gt;' has no attribute 'body'。我将它包装在 try 和 except 中并且有效,但另一个不起作用(阅读,'我不明白如何使用它')。似乎它会检查主体是否存在,但是在 pass 命令之后,它仍然只是运行代码。
    • 糟糕,在其他示例中应该是继续,而不是通过。固定。
    • 现在说得通了。再次感谢您!
    最近更新 更多