나는

2014-12-12 1 views
0

내가이 라인을 실행하고 있습니다 RSS 피드에서 이미지를 잡으려고 싶습니다나는

views.py

def pull_feed(feed_url, posts_to_show=5): 
    feed = feedparser.parse(feed_url) 
    posts = [] 
    for i in range(posts_to_show): 
     pub_date = feed['entries'][i].updated_parsed 
     published = date(pub_date[0], pub_date[1], pub_date[2]) 
     posts.append({ 
      'title': feed['entries'][i].title, 
      'summary': feed['entries'][i].summary, 
      'link': feed['entries'][i].link, 
      'content': feed['entries'][i].content, 
      'date': published, 
     }) 
    return {'posts': posts} 

my_template.html

 {% for post in posts.posts %} 
       <h3>{{ post.title }}</h3> 
       {{ post.content }} 
       <hr/> 
     {% endfor %} 

을하지만 내가하고 싶은 post.image와 같은 것이거나 post.content에서 (RSS 블로그의) 이미지를 잡으십시오. 그 이유는 다음과 같습니다. 결과 :

[{'base': u'http://websiteexample.com/feed/', 'type': u'text/html', 'value': u'<p><a href="http://websiteexample.com/wp-content/uploads/2014/12/imageexample.png">}] 

RSS에서 이미지를 가져 오는 방법은 무엇입니까? 나중에 데이터베이스에 저장하고 포스트 복제와 같은 것을 만들 것입니다.

답변

2

당신은 이미지처럼 보이는 '값'필드 내용의 첫 번째 URL을 구문 분석하는 파이썬의 re 모듈을 사용할 수 있습니다 (즉,이 PNG/JPEG/JPG와 같은 확장) 다음

import re 

# inside your for i in range(posts_to_show) loop: 
value = feed['entries'][i].content[0]['value'] 
image_url = re.search('(?P<url>http?://[^\s]+(png|jpeg|jpg))', value).group("url") 

을 수행 할 수 있습니다 게시물에 image_url을 추가하십시오.

posts.append({ 
     'title': feed['entries'][i].title, 
     'summary': feed['entries'][i].summary, 
     'link': feed['entries'][i].link, 
     'content': feed['entries'][i].content, 
     'date': published, 
     'image_url': image_url, 
    }) 
+0

'값'문자열에는 무엇을 입력해야합니까? 왜냐하면 나는 다음과 같은 오류가 발생하기 때문에 : 목록 색인은 str이 아닌 정수 여야한다. –

+0

'value'는 post.content에서 가져온 사전의 키이고, 사전은 대괄호 안에 실제로 들어있다. 실제로 사전 목록 (또는 하나의 사전이있는 목록)은 'value'에 도달하기 위해 목록 색인으로 들어가야합니다. post.content [0] [ 'value'] – brobas