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

标签 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.

加星标的部分是我遇到问题的地方。我正在尝试浏览其中写有“Cricketbot,给我澳大利亚新闻”的评论。不幸的是,如果评论的主体不存在,即评论为空,代码将返回一个属性错误,并指出评论没有属性“body”。

如何解决这个问题?

最佳答案

它通常有助于添加堆栈跟踪,以便人们可以看到实际的错误。但是,作为 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
    ...

但是,当运行上述任何解决方案时,您实际上并没有处理提交的所有评论,因为您遗漏了隐藏在 MoreComments 对象后面的任何内容 [ ref ].要将 MoreComments 对象替换为 some (全部替换可能非常低效)评论,需要在展平树之前使用 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 个额外评论的请求。您可以随心所欲地使用这些值,但请注意,每次替换都需要一个额外的请求(2 秒),有些只产生一条评论。

希望对您有所帮助。

关于python - 在praw中,我正在尝试打印评论正文,但是如果我遇到空评论怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17430409/

相关文章:

python - Praw:如何根据创建日期过滤搜索结果?

python - 同时运行的多个 Python 实例限制为 35 个

python 异步连接

python - Django,第一次迁移时auth文件夹下的models.py如何创建初始表?

node.js - 通过浏览器和 NodeJS 请求访问 Reddit json api 时,其行为有所不同

javascript - reddit 和 twitch api 的速率限制如何工作?

python - 无法从在 Docker 容器中运行的 Django 应用程序连接到远程 PostgreSQL 实例

python3 生成大列表时出现内存错误

java - 使用 Java 仅访问一次 Reddit .json 页面时出现 HTTP 429 请求过多

javascript - 尝试使用 Javascript 创建 Reddit 编程 API