使用Flask和BeautifulSoup 3及Python 2.7.8在HTML中显示元素

0 投票
1 回答
720 浏览
提问于 2025-04-18 18:52

问题是: 我有一个@app.route和相应的def(),它显示了从“http://annotaria.web.cs.unibo.it/documents/”获取的一系列网址。 我该如何以HTML格式展示这些网址呢?当我点击http://localhost:5000/articoli时,我希望能看到我的网址列表。

非常感谢

@app.route('/articoli', methods=['GET'])
def lista_articoli():
lista = []
import urllib2
from bs4 import BeautifulSoup
url = urllib2.urlopen`http://annotaria.web.cs.unibo.it/documents/.read()`
soup = BeautifulSoup(url)
for row in soup.findAll('a'):
    if row.parent.name == 'td':
        if row["href"] :
            myArticle = row["href"]
            if '.html' in myArticle:
                print myArticle
                lista.append({'url':myArticle}) }

1 个回答

0

要做到这一点,你需要让你的函数返回一个叫做 render_template 的方法,并把你的网址列表传给它。

在你的函数最后,试试这样:

render_template("articoli.html", lista = lista)

你还需要在一个名为 templates 的文件夹里保存一个对应的 articoli.html 模板,这个文件夹要和你的Python脚本放在同一个地方。在这个HTML模板里,你需要指定Flask/Jinja放置你提供的网址列表的位置,在这个例子中就是 {{lista}}

具体内容可以参考 Flask的文档

撰写回答