Reputation: 3090
Given:
<html>
<style>
@font-face
{font-family:"MS Mincho"}
</style>
</html>
How could I add @font-face {font-family:"MS Gothic"}
to this style tag?
I'm using Beautiful soup 4 and the following code to select the style, but unsure how to add the new style after the first:
code = BeautifulSoup(html, 'html.parser')
s = code.select('style')
Upvotes: 2
Views: 1141
Reputation: 20008
To add a new tag to the HTML, you can use the .append()
method:
You can add to a tag’s contents with
Tag.append()
. It works just like calling.append()
on a Python list.
In your example:
from bs4 import BeautifulSoup
html = """
<html>
<style>
@font-face
{font-family:"MS Mincho"}
</style>
</html>
"""
soup = BeautifulSoup(html, "html.parser")
soup.select_one("style").append('@font-face\n{font-family:"MS Gothic"}')
print(soup)
Upvotes: 2