python - 嵌套的 For 循环很快停止(初学者)
问题描述
我在我编写的脚本中使用了几个嵌套的 For 循环来抓取 Reddit 的 API,但在抓取单个帖子后脚本似乎停止了。它一直运行在循环中,但无论出于何种原因都不会重复该过程。有人知道这里发生了什么吗?
for i in subreddit:
submission = reddit.submission(id=i.id)
comments = submission.comments
ts = datetime.utcfromtimestamp(i.created_utc).strftime('%Y-%m-%d %H:%M:%S')
tree = ('Comment section:')
for comment in comments:
body = ('----\nComment:' + comment.body + '\n----')
tree = tree + body
if len(comment.replies) > 0:
for reply in comment.replies:
bodyrply = ('\nREPLY: \n' + reply.body + '----')
tree = tree + bodyrply
else:
tree = tree
continue
filewriter.writerow({'title': i.title,'author': i.author,
'original content': i.is_original_content,
'selfpost': i.is_self,
'time created': ts,
'stickied': i.stickied,
'locked': i.locked,
'NSFW': i.over_18,
'selftext': i.selftext,
'comment forest': tree,
'number of comments': i.num_comments,
'score': i.score,
'upvote ratio': i.upvote_ratio,
'permalink': i.permalink,
'url': i.url})
解决方案
这不是最终的答案,但它可能有助于缩小问题的范围。在代码中添加一些检查以确认初始数据是您所期望的。
print("len sr =", len(subreddit)) # is this a valid list greater than 1 ?
for i in subreddit:
print("i =", i) # what object are you dealing with ?
submission = reddit.submission(id=i.id)
comments = submission.comments
ts = datetime.utcfromtimestamp(i.created_utc).strftime('%Y-%m-%d %H:%M:%S')
tree = ('Comment section:')
print("len cmts =", len(comments)) # are there any comments ?
for comment in comments:
body = ('----\nComment:' + comment.body + '\n----')
tree = tree + body
if len(comment.replies) > 0:
for reply in comment.replies:
bodyrply = ('\nREPLY: \n' + reply.body + '----')
tree = tree + bodyrply
else:
pass # tree = tree
print("i2 =", i) # make sure the code got this far
continue
推荐阅读
- python - scipy 稀疏矩阵上的 sklearn train_test_split 给出错误的结果
- vue.js - 将 vue 1 迁移到 vue 2
- wpf - Oxyplot- WPF:将数据从双重列表添加到数据点
- python - Django Stripe Connect 帐户创建
- python - 初学者打开资源管理器以显示文件夹内容
- node.js - 尝试实现节点 js 多图时出现问题
- python - PyQt4 如何让 QWidget 始终位于顶部?
- java - 将“2个背景”设置为一个按钮
- io - Flutter:权限被拒绝写入文件
- javascript - jQuery在使用ajax创建表后从表中获取nth:child