Python 将变量转换为html
我对烧瓶不熟悉。我有一个python脚本,可以从几个网站上获取数据。它运行良好,但我想在一个简单的html页面中显示结果,所以我开始查看Flask。在我的脚本中,我基本上有这段代码Python 将变量转换为html,python,flask,Python,Flask,我对烧瓶不熟悉。我有一个python脚本,可以从几个网站上获取数据。它运行良好,但我想在一个简单的html页面中显示结果,所以我开始查看Flask。在我的脚本中,我基本上有这段代码 #main.py for shop in shops: print shop service = get_services(shop) for s in service: print s #scraper.py shops = { 'Shop Alpha':'htt
#main.py
for shop in shops:
print shop
service = get_services(shop)
for s in service:
print s
#scraper.py
shops = {
'Shop Alpha':'https://www.shopalpha.com',
'Shop Bravo': 'https://www.shopbravo.com',
'Shop Charlie': 'https://www.shopcharlie.com'
}
def get_services(shop):
r = requests.get(shops[shop])
soup = BeautifulSoup(r.text, "html.parser")
service = service_scraper(shop, soup)
# here I call my scraping methods
return service
当我运行脚本时,将生成以下输出:
Shop Alpha
Cars
Bikes
Shop Bravo
Boats
Shop Charlie
Helicopters
Planes
Tanks
我试图添加这段代码
app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
return render_template('index.html',**locals())
app.run(debug=True)
向html页面传递变量的最简单方法是什么?我想要的是在html中使用for循环。可能吗?那么我需要通过什么考试呢
例如,我可以传递变量以便在html中使用类似的内容:
<body>
{% for shop in shops %}
<h4>{{ shop }}</h4>
{% endfor %}
</body>
{商店中的商店%}
{{shop}
{%endfor%}
以下是如何做到这一点
app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
# Get shops
shops = get_shops()
return render_template('index.html', shops = shops)
app.run(debug=True)
尝试在数据库或文件中保存scraped数据,以避免每次加载index
时对URL进行爬网,然后在index
端点中读取数据,然后在index.html
<body>
{% for shop in shops %}
<h4>{{ shop }}</h4>
{% endfor %}
</body>
{商店中的商店%}
{{shop}
{%endfor%}
我会考虑将WaZa指向文档,因为这类问题在容易找到的教程中得到了很好的覆盖:但是我的问题是在Python代码中,我在for循环中遍历商店,并且在每个商店中调用GETSyService并通过当前的商店。这是我在html中无法做到的。@wazza不建议在呈现页面时抓取链接。相反,您需要做的是对商店的链接进行爬网,并将结果保存在文件(或数据库)中,然后从该文件(或数据库)中读取商店。要保持数据新鲜,请使用cron
作业偶尔获取一次数据。