Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add strings with tags as HTML using BeautifulSoup

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading