I am constructing HTML as part of a bigger project. The construction works, no issues with that. However I fear that the code is too verbose or that I am not using the full power of BeautifulSoup.
For Example: I am generating a div tag of class editorial that wraps a div of class editorial-title, editorial-image, editorial-subtitle, editorial-article in that order.
Sample 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>
Here is the long code that works for small demo version of what I am trying to do -
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())
It does the job but I feel its too long. Is there a more elegant way to achieve this?