2

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')

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.