Есть ли более короткий способ или способ Pythoni c для создания пользовательского html, который следует шаблону, используя BeautifulSoup? - PullRequest
5 голосов
/ 22 февраля 2020

Я строю HTML как часть большого проекта. Строительные работы, никаких проблем с этим. Однако я боюсь, что код слишком многословен или что я не использую всю мощь BeautifulSoup.

Например: я генерирую тег div класса editorial, который включает div класса editorial-title, editorial-image, editorial-subtitle, editorial-article в указанном порядке.

Пример HTML -

<div class="editorial">
    <div class="editorial-title">Hello</div>
    <div class="editorial-image"><img src="https://images.dog.ceo/breeds/collie-border/n02106166_2595.jpg"></div>
    <div class="editorial-subtitle">world</div>
    <div class="editorial-article">Yeah. But Parasite? It should have been Gone with the Wind!</div>
</div>

Вот длинный код, который работает для небольшой демонстрационной версии того, что я пытаюсь сделать -

from bs4 import BeautifulSoup

title = "Hello"
subtitle = "world"
image_url = "https://images.dog.ceo/breeds/collie-border/n02106166_2595.jpg"
article = "But Parasite? It should have been Gone with the Wind!"

editorial_container = BeautifulSoup('', 'html.parser')
editorial_container_soup = editorial_container.new_tag('div', attrs={"class": "editorial"})

editorial_soup = BeautifulSoup('', 'html.parser')

editorial_title = editorial_soup.new_tag('div', attrs={"class": "editorial-title"})
editorial_image = editorial_soup.new_tag('div', attrs={"class": "editorial-image"})
image = editorial_soup.new_tag('img', src=image_url)
editorial_subtitle = editorial_soup.new_tag('div', attrs={"class": "editorial-subtitle"})
editorial_article = editorial_soup.new_tag('div', attrs={"class": "editorial-article"})

editorial_title.append(title)
editorial_image.append(image)
editorial_subtitle.append(subtitle)
editorial_article.append(article)

editorial_soup.append(editorial_title)
editorial_soup.append(editorial_image)
editorial_soup.append(editorial_subtitle)
editorial_soup.append(editorial_article)

editorial_container_soup.append(editorial_soup)
editorial_container.append(editorial_container_soup)
print(editorial_container.prettify())

Это делает работа, но я чувствую, что это слишком долго. Есть ли более элегантный способ добиться этого?

1 Ответ

3 голосов
/ 22 февраля 2020

Для задачи, которую вы выполняете, я настоятельно рекомендую использовать шаблон Jinja вместо BeautifulSoup.

Если вы использовали Jinja, вам просто нужно передать словарь с редакционной информацией в editorial.html, который может выглядеть следующим образом:

<!-- reusable editorial.html -->
<div class="editorial">
    <div class="editorial-title">{{ title }}</div>
    <div class="editorial-image"><img src="{{ image }}"></div>
    <div class="editorial-subtitle">{{ subtitle }}</div>
    <div class="editorial-article">{{ article }}</div>
</div>

Включите editorial.html в следующее Файл html, который будет загружен flask. В этом примере это будет базовый шаблон.

<!-- template.html -->
<html>
    <head>
        <title>Jinja Sample</title>
    </head>
<body>
    {% include "editorial.html" %} 
</body>
</html>

Использование Flask

Запустите приложение flask, как показано ниже:

from flask import Flask, render_template
app = Flask(__name__)


@app.route("/")
def editorial_test():
    editorial_info = {
        "title" : "Hello",
        "image" : "https://images.dog.ceo/breeds/collie-border/n02106166_2595.jpg",
        "subtitle" : "world",
        "article" : "Yeah. But Parasite? It should have been Gone with the Wind!"
    }

    return render_template('template.html', editorial=editorial_info)


if __name__ == '__main__':
    app.run(debug=True)

Я не проверял код выше. Посмотрите этот превосходный учебник для дальнейшего разъяснения.

Рендеринг файлов напрямую

Если вы не хотите использовать Flask, вы может отобразить веб-страницу следующим образом (я предполагаю, что все файлы находятся в одном каталоге):

import jinja2

editorial_info = {
        "title" : "Hello",
        "image" : "https://images.dog.ceo/breeds/collie-border/n02106166_2595.jpg",
        "subtitle" : "world",
        "article" : "Yeah. But Parasite? It should have been Gone with the Wind!"
    }

templateLoader = jinja2.FileSystemLoader(searchpath="./")
templateEnv = jinja2.Environment(loader=templateLoader)
TEMPLATE_FILE = "template.html"
template = templateEnv.get_template(TEMPLATE_FILE)
outputText = template.render(editorial_info) 

print(outputText)

Вывод

<html>
    <head>
        <title>Jinja Sample</title>
    </head>
<body>
    <div class="editorial">
    <div class="editorial-title">Hello</div>
    <div class="editorial-image"><img src="https://images.dog.ceo/breeds/collie-border/n02106166_2595.jpg"></div>
    <div class="editorial-subtitle">world</div>
    <div class="editorial-article">Yeah. But Parasite? It should have been Gone with the Wind!</div>
</div>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...