【问题标题】:I would like to catch the image from RSS feed我想从 RSS 提要中捕捉图像
【发布时间】:2014-12-12 21:08:36
【问题描述】:

我正在执行这些行:

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}

我的模板.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 获取图片?稍后我会将其保存在我的数据库中并进行类似后复制的操作。

【问题讨论】:

    标签: python django rss feedparser


    【解决方案1】:

    您可以使用 python 的 re 模块解析出内容“值”字段中看起来像图像的第一个 url(即具有类似 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,
        })
    

    【讨论】:

    • 我应该在'value'字符串上输入什么?因为我收到以下错误:列表索引必须是整数,而不是 str
    • 我更新了我的答案,'value' 是你从 post.content 获得的字典中的一个键,错过了字典实际上在方括号内的部分,所以它实际上是一个字典列表(或一个字典的列表),所以必须深入到该列表索引以获取“值”,所以它就像:post.content[0]['value']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2023-03-16
    相关资源
    最近更新 更多