在praw中,我正在尝试打印评论正文,但如果我遇到空评论怎么办?

sun*_*nny 7 python reddit

我试图打印来自subreddit顶部帖子的所有评论,以便我的机器人可以分析它们.我让它在当天早些时候运行,但我现在尝试运行它并且遇到了错误.

这是我的代码:

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.
Run Code Online (Sandbox Code Playgroud)

主演部分是我遇到问题的地方.我试图通过评论中写有"Cricketbot,给我澳大利亚新闻"的评论.不幸的是,如果注释的主体不存在,即注释为空,则代码返回属性错误,并表示注释没有属性"body".

如何解决这个问题?

bbo*_*boe 15

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

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

try:
    if "Cricketbot..."
        ...
except AttributeError:
    pass
Run Code Online (Sandbox Code Playgroud)

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

第一种是明确检查属性是否存在:

for comment in flat_comments:
    if not hasattr(comment, 'body'):
        continue
    ...
Run Code Online (Sandbox Code Playgroud)

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

for comment in flat_comments:
    if not isinstance(comment, praw.objects.Comment):
        continue
    ...
Run Code Online (Sandbox Code Playgroud)

但是,在运行上述任何解决方案时,您实际上并未处理提交中的所有注释,因为您遗漏了隐藏在MoreComments对象后面的任何内容[ 参考 ].MoreComments要用一些替换对象(替换所有可能非常低效的)注释,需要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)
Run Code Online (Sandbox Code Playgroud)

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

我希望有所帮助.