flask构建自动化测试平台2-开始头条项目

2-开始头条项目

本文使用的RSS地址经常会失效,请以最新github代码为准。

我们将创建一个头条应用程序,显示最新的新闻标题,天气信息,和货币汇率。

在本章中,我们将介绍RSS源并展示如何自动使用它们从特定出版物中检索最近的新闻报道。在下一章中,我们会讨论如何使用模板来显示检索到的标题和摘要文章给我们的用户。第4章,我们头条页面项目的用户输入,将显示你如何从用户那里获得输入,以便他们可以定制他们的体验,也看看如何将天气和货币数据添加到我们的应用程序。我们会完成在第5章“改善我们头条项目的用户体验”一文中关注项目添加一些CSS样式并查看如何记住用户的偏好。

到本章结束时,您将学会如何创建更复杂的Flask应用。我们将从真实世界的新闻故事中提取原始数据并构建HTML格式化将其显示给我们的用户。您还将学习更多关于路由的知识 - 也就是说不同的URL会触发我们应用程序代码的不同部分。

在本章中,我们将介绍以下主题:

  • RSS和RSS源简介

技术支持QQ群: 144081101 591302926 567351477 本文最新版本

RSS和RSS源简介

我们需要安装feedparser:feedparser。

  • 问题,如何寻找python库?

python测试开发库PYPI

pip3 install --user feedparser

主要的RSS有WordPress和Blogger,通常会有如下图标。

image.png

BBC news的rss为: http://feeds.bbci.co.uk/news/rss.xml

下面的代码需要对HTML有一定的了解,初学者可以参考:http://www.w3school.com.cn/html/index.asp

import feedparser
from flask import Flask

app = Flask(__name__)

RSS_FEEDS = {'ft': 'http://www.ftchinese.com/rss/feed',
             'zhihu': 'https://www.zhihu.com/rss',
             'people': 'http://www.people.com.cn/rss/politics.xml',
             'iol': 'http://www.iol.co.za/cmlink/1.640'}


@app.route("/")
@app.route("/<publication>")
def get_news(publication="ft"):
    feed = feedparser.parse(RSS_FEEDS[publication])
    first_article = feed['entries'][0]
    return """<html>
    <body>
        <h1>Headlines </h1>
        <b>{0}</b> </ br>
        <i>{1}</i> </ br>
        <p>{2}</p> </ br>
    </body>
</html>""".format(first_article.get("title"),
                  first_article.get("published"),
                  first_article.get("summary"))


if __name__ == "__main__":
    app.run(host='0.0.0.0',port=8000, debug=True)

执行:

$ curl http://172.20.15.200:8000/iol
<html>
    <body>
        <h1>Headlines </h1>
        <b>IEC still unable to confirm addresses of 2.8 million citizens</b> 
        <i>Wed, 07 Mar 2018 17:26:00 GMT</i>
        <p>The Independent Electoral Commission still does not have addresses for 2.8 million South Africans ahead of the 2019 general elections.</p>
    </body>
</html>andrew@andrew-PowerEdge-T630:~/code/Flask-Building-Python-Web-Services/Module 1$ curl http://172.20.15.200:8000/cnn
<html>
    <body>
        <h1>Headlines </h1>
        <b>In Lesotho, women say they're finding their abortions on Facebook</b> 
        <i>None</i>
        <p>None</p>
    </body>
</html>andrew@andrew-PowerEdge-T630:~/code/Flask-Building-Python-Web-Services/Module 1$ curl http://172.20.15.200:8000/test
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>KeyError: 'test' // Werkzeug Debugger</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css"
        type="text/css">
    <!-- We need to make sure this has a favicon so that the debugger does

...

图片.png

参考资料

links