使用模板和 JSON 输出数据 HTML



对于我来说,使用模板和 JSON 作为数据输出(符合 AMP 标准的(HTML 的好方法是什么?我有一个不错的小python脚本:

import requests
import json
from bs4 import BeautifulSoup
url = requests.get('https://www.perfectimprints.com/custom-promos/20492/Beach-Balls.html')
source = BeautifulSoup(url.text, 'html.parser')
products = source.find_all('div', class_="product_wrapper")
infos = source.find_all('div', class_="categories_wrapper")
def get_category_information(category):
category_name = category.find('h1', class_="category_head_name").text
return {
"category_name": category_name.strip()
}
category_information = [get_category_information(info) for info in infos]
with open("category_info.json", "w") as write_file:
json.dump(category_information, write_file)
def get_product_details(product):
product_name = product.find('div', class_="product_name").a.text
sku = product.find('div', class_="product_sku").text
product_link = product.find('div', class_="product_image_wrapper").find("a")["href"]
src = product.find('div', class_="product_image_wrapper").find('a').find("img")["src"]
return {
"title": product_name,
"link": product_link.strip(),
"sku": sku.strip(),
"src": src.strip()
}
all_products = [get_product_details(product) for product in products]
with open("products.json", "w") as write_file:
json.dump({'items': all_products}, write_file)
print("Success")

这会生成我需要的 JSON 文件。但是,我现在需要使用这些 JSON 文件并将其输入到我的模板(gist(中,无论它说{{ JSON DATA HERE }}.

我什至不知道从哪里开始。我对 JavaScript 最满意,所以如果可能的话,我想使用它。我想到了与 Node.js 有关的东西。

下面介绍如何单独使用模板引擎呈现 HTML,并使用它来返回纯 HTML:

from jinja2 import Template
me = Template('<h1>Hello {{x}}<h1>')
html = me.render({'x': 'world'})
return html

html是呈现的 HTML 字符串。或者,您可以从文件进行渲染:

from jinja2 import Template
with open('your_template.html') as file_:
template = Template(file_.read())
html = template.render(your_dict)
return html

由于您将以一种或另一种方式生成 HTML,因此使用模板引擎将为您节省大量时间。您也可以为列表 %} 中的项目执行 {% 操作,这样的事情将大大简化您的任务。