2014-09-04 30 views

回答

4

您:

人在亞利桑那州失蹤女孩死亡被捕:在網頁上

from django.http import HttpResponse 
import feedparser 

def index(content): 
    YahooContent = feedparser.parse ("http://news.yahoo.com/rss/") 
    for feed in YahooContent.entries: 
      content = (feed.title + ": " + "\n"+feed.link + "\n" + feed.published + "\n") 
      return HttpResponse(content) 

結果需要收集列表中的提要,然後在循環後返回一個HttpResponse實例:

content = [] 
for feed in YahooContent.entries: 
    content.append(feed.title + ": " + "\n" + feed.link + "\n" + feed.published) 

return HttpResponse('\n'.join(content)) 

另一種選擇,將跟隨Django philosophies約的關注點分離,將是create and render a template並將數據傳遞到模板背景:

  • 創建一個模板,讓我們說index.html包含以下內容

    <table> 
        <tr> 
         <th>Title</th> 
         <th>Link</th> 
         <th>Published</th> 
        </tr> 
        {% for entry in entries %} 
         <tr> 
          <td>{{ entry.title }}</td> 
          <td>{{ entry.link }}</td> 
          <td>{{ entry.published }}</td> 
         </tr> 
        {% endfor %} 
    </table> 
    
  • 將模板放入您的應用或項目的templates目錄中

  • 使用,例如使其在視圖中,render_to_response()

    from django.shortcuts import render_to_response 
    import feedparser 
    
    def index(content): 
        entries = feedparser.parse ("http://news.yahoo.com/rss/").entries 
        return render_to_response('index.html', {'entries': entries}) 
    
+0

工作顯示所有內容,但仍顯示爲一個單一的字符串。我希望能夠分離新聞並顯示超鏈接。 – Amir 2014-09-04 18:46:33

+0

@Amir好吧,我已經爲您提供了一種更好的方法。 – alecxe 2014-09-04 18:55:14

+0

非常感謝,我會盡力的。 – Amir 2014-09-04 19:02:25

0

你的「回報」語句是裏面的for循環,由於它是第一次迭代本身回國後,因此給只有一個而不是所有提要,以便能夠返回所有需要的提要,以構建所有提要的列表,然後返回該提要。

+1

5分鐘後我看不出重複的答案。而且,如果沒有實際的代碼,這也無濟於事。 – alecxe 2014-09-04 18:48:06

+0

我很抱歉,但在我打開這個問題之前,我看到了你的回答,然後去閱讀我的郵件,然後鍵入答案。 – 2014-09-04 18:50:36