Add strings with tags as HTML using BeautifulSoup

Question:

I have a html table data formatted as a string I’d like to add a HTML row.

Let’s say I have a row tag tag in BeautifulSoup.

<tr>
</tr>

I want to add the following data to the row which is formatted as a string (including the inner tags themselves)

<td><a href="www.example.com">A</a></td><td>A1<time>(3)</time>, A2<time>(4)</time>, A3<time>(8)</time></td>

Is there an easy way to do this through BeautifulSoup or otherwise (for example, I could convert my document to a string, but I would make it harder to find the tag I need to edit). I’m not sure If I have to add those inner tags manually.

Asked By: hedebyhedge

||

Answers:

Try tag.append:

from bs4 import BeautifulSoup

html = "<tr></tr>"
my_string = r'<td><a href="www.example.com">A</a></td><td>A1<time>(3)</time>, A2<time>(4)</time>, A3<time>(8)</time></td>'


soup = BeautifulSoup(html, "html.parser")
soup.find("tr").append(BeautifulSoup(my_string, "html.parser"))

print(soup)

Prints:

<tr><td><a href="www.example.com">A</a></td><td>A1<time>(3)</time>, A2<time>(4)</time>, A3<time>(8)</time></td></tr>
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.