将文本解析为htm时出现轻微问题

2024-05-15 01:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

嗯,这可能很简单,但也可能很复杂。我在Django框架内设置一个SEO友好的Twitter提要时遇到了一个问题。大多数繁重的工作都是作为模板标记blog_tags.py文件完成的,如下所示:

@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 }

所有的工作都很好-它返回我想要的一切,目前它剥离了标签,并替换为Twitter友好的标签。但是,客户端显示的是:

enter image description here

我被困在如何工作,使客户端的html元素呈现为html元素,而不是预先格式化的文本


Tags: inurldatesettingshtmlfeedstatustwitter

热门问题