<p>下面是我如何解决它的,创建了一个if语句来检查[“data”][“replies”]是否是字典,在这种情况下执行代码,如果不是,则继续循环。你知道吗</p>
<p>这是它的样子,再次感谢阿迪蒂亚和高约:</p>
<pre><code>def getcommentsforpost(subredditname,postid,):
reditpath = '/r/' + subredditname + '/comments/' + postid
redditusual = 'https://www.reddit.com'
parameters = '.json?'
totalpath = redditusual + reditpath + parameters
p = requests.get(totalpath, headers = {'User-agent' : 'Chrome'})
result = p.json()
totallist = []
# the result object is a list with two dictionaries, one with info on the post, and the second one
# with all the info regarding the comments and their respective replies
a = result[0]["data"]["children"][0]["data"]
abody = a["selftext"]
aauthor = a["author"]
ascore = a["score"]
adictionary = {"commentauthor" : aauthor , "comment" : abody , "Type" : "Post",
"commentscore" : ascore}
totallist.append(adictionary)
for i in result[1]["data"]["children"]:
ibody = i["data"]["body"]
iauthor = i["data"]["author"]
iscore = i["data"]["score"]
idictionary = {"commentauthor" : iauthor , "comment" : ibody , "Type" : "post_comment",
"commentscore" : iscore}
totallist.append(idictionary)
if isinstance(i["data"]["replies"],dict) :
replylists = i["data"]["replies"]["data"]["children"]
for j in replylists:
jauthor = j["data"]["author"]
jbody = j["data"]["body"]
jscore = j["data"]["score"]
jdictionary = {"commentauthor" : jauthor , "comment" : jbody , "Type" : "comment_reply" ,
"commentscore" : jscore }
totallist.append(jdictionary)
elif type(i["data"]["replies"]) == 'str':
continue
finaldf = pd.DataFrame(totallist)
return(finaldf)
</code></pre>