将文本解析为html的轻微问题

时间:2017-06-25 16:33:27

标签: python html django twitter html-parsing

嗯,这可能很容易,但可能很复杂。我有一个问题是在Django框架内设置一个SEO友好的Twitter提要。大部分繁重工作都是作为模板标签@register.inclusion_tag('blog/frame/twitter.html') def show_latest_tweets(): tweets = [] try: """The import error is here to catch any server migrations were the tweepy package not to be found in site_packages""" import tweepy except: tweets.append({'status': 'There was a problem referencing our tweets. Please inform our webmaster.', 'relative_date': 'Just now'}) raise ImportError # OAuth process, using the keys and tokens auth = tweepy.OAuthHandler(settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_KEY'], settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_SECRET']) auth.set_access_token(settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_ACCESS_TOKEN'], settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_ACCESS_TOKEN_SECRET']) # Creation of the actual interface, using authentication api = tweepy.API(auth) user = 'FFXVEN' avatar_url = api.get_user(screen_name='@'+user).profile_image_url i = 0 for tweet in tweepy.Cursor(api.user_timeline, screen_name='@'+user).items(): if 'RT' not in tweet.text: if i <= 4: status = tweet.text hashtags = [word for word in status.split() if word[0] == "#"] #Find hashtags in tweet and create a string to contain <a href="https://twitter.com/search?q=" + hashtag>#hashtag</a> for hashtag in hashtags: if hashtag.endswith((',',';','.')): hashtag = hashtag[:-1] status = status.replace(hashtag, '<a href="https://twitter.com/search?q={}">{}</a>'.format(hashtag[1:], hashtag)) relative_date = tweet.created_at tweets.append({'user': user, 'avatar_url': avatar_url, 'status': html.unescape(status), 'relative_date': relative_date}) i += 1 else: break else: continue return { "tweets": tweets } 文件完成的,如下所示:

[
  {
    "_id": "70001",
    "name": "peter"
  },
  {
    "_id": "70002",
    "name": "john"
  },
  {
    "_id": "70003",
    "name": "joseph"
  }
]

一切运作良好 - 它返回我想要的所有内容,目前它会删除主题标签并用Twitter友好主题标签替换它们。但是,客户端这是显示的内容:

scoped slot

我一直坚持我会如何工作,以便客户端html元素呈现为html元素而不是预先格式化的文本?

1 个答案:

答案 0 :(得分:2)

{{ tweet.status|safe }

尝试安全模板过滤器