2013-07-02 26 views
6

我想從subreddit的頂端帖子打印所有評論,以便我的機器人可以分析它們。我已經在當天早些時候運行它,但是我現在嘗試運行它,並且遇到了一個錯誤。在praw中,我試圖打印評論主體,但如果遇到空的評論怎麼辦?

這裏是我的代碼:

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」。

如何解決這個問題?請致電GitHub page for the bot

回答

13

它通常有助於添加堆棧跟蹤,以便人們可以看到實際的錯誤。然而,作爲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對象(更換全部是極其低效的)意見的要求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秒),有些只會產生少至一條評論。

我希望有幫助。

+0

非常感謝!道歉,確實是'AttributeError:''沒有屬性'body'。我把它包裝在嘗試和除了和工作,但另一個不工作(閱讀,'我不明白如何使用它')。它似乎檢查是否存在該主體,但是在傳遞命令之後,它只是運行代碼。 – sunny

+1

糟糕,它應該是一個繼續,而不是在其他例子中通過。固定。 – bboe

+0

現在有道理。再一次感謝你! – sunny

相關問題