Praw Reddit 网络爬虫错误"object has no attribute"



我正试图使用Reddit Web爬网程序从特定的子版块中提取热门评论,并将其保存在.csv文件中。

这是我的代码:

import datetime
import praw
import pandas as pd
reddit = praw.Reddit(client_id='',
client_secret='',
password='',
user_agent='',
username='')
#Reddit Crawler
list_counter = 0
sr_list = ['politics', 'conservative', 'liberal', 'libertarian', 'donaldtrump', 'joebiden', 'democrats', 'republican']
data = []
comments = []
while list_counter < len(sr_list):
subreddit = reddit.subreddit(sr_list[list_counter]).top(time_filter='month', limit=1) #Change limit for number of threads, .new/.hot
for s in subreddit:  # for every submission in the subreddit
# fetch top level comments
for c in s.comments:
c_time = datetime.datetime.fromtimestamp(c.created_utc) #Convert format of comment time (Y:M:D , H:M:S)
comments.append([c.subreddit, c._submission, 'Comment', s.title, c.author, c_time, c.score, c.body])
#May not need c._submission
s_time = datetime.datetime.fromtimestamp(s.created_utc) #Convert format of threadRE time
data.append([s.subreddit, s.id,'Thread', s.title, s.author, s_time, s.score, s.selftext])
list_counter+= 1
#Export to CSV#
df = pd.DataFrame(data, columns=['Subreddit Name','Thread ID', 'Thread/Comment', 'Thread Title', 'Author',
'Timestamp','Score','Content'])
df1 = pd.DataFrame(comments, columns=['Subreddit Name','Thread ID','Thread/Comment', 'Thread Title', 'Author',
'Timestamp','Score','Content'])
result = pd.concat([df, df1])
result.to_csv('Raw Data.csv', index=False)

该代码在大多数情况下都运行良好,但对于大量的帖子和评论,它会返回以下错误消息:

Traceback (most recent call last):
File "/Users/robin/Documents/Python/code/Jonckr Reddit Web Crawler.py", line 23, in <module>
c_time = datetime.datetime.fromtimestamp(c.created_utc) #Convert format of comment time (Y:M:D , H:M:S)
AttributeError: 'MoreComments' object has no attribute 'created_utc'
Process finished with exit code 1

我几乎是一个编程爱好者,所以我不知道如何解决这个问题。非常感谢您的帮助。

提前谢谢。

在Praw文档中,它声明这些MoreComments对象是加载更多评论的表示,继续Reddit上遇到的这个线程链接。

为了解决这个问题,他们建议如下:

from praw.models import MoreComments
for top_level_comment in submission.comments:
if isinstance(top_level_comment, MoreComments):
continue

在代码的上下文中,尝试以下操作:

for c in s.comments:
if isinstance(c, MoreComments):
continue
c_time = datetime.datetime.fromtimestamp(c.created_utc) #Convert format of comment time (Y:M:D , H:M:S)
...

相关内容

  • 没有找到相关文章

最新更新