brisharpiro
brisharpiro

Reputation: 35

How to prepend to an HTML element?

How do I prepend to an HTML div using Python using element IDs?

For example, if I have the following HTML code in a file called "test.html":

<div id="insertHere">
</div>

And I want to insert the following line <li> Item 1 </li> into the div element with id "insertHere." So I want the resulting markup to look like this:

<div id="insertHere">
   <li> Item 1 </li>
</div>

How do I do this in Python? I tried doing the following:

myfile = open('test.html', 'w')
myfile.write('<li> Item 1 </li>')
myfile.close()

but the problem with myfile.write is that it does not give me an option to specify to place the list item in the div with id "insertHere."

I suppose this would be similar to the prepend() function in Javascript.

Upvotes: 0

Views: 173

Answers (1)

Aziz Khelifi
Aziz Khelifi

Reputation: 46

You can use BeautifulSoup

from bs4 import BeautifulSoup

# Importing 
with open("doc.html", "r") as file:
  html = file.read() 


# Changing 

soup = BeautifulSoup(html)

myId = soup.find(id='insertHere')

new_tag = soup.new_tag("li")
new_tag.append("Item 1")

myId.append(new_tag)

html = str(soup)

# Saving

with open("doc.html", "w") as file:
  file.write(html)

output:

<div id="insertHere">
<li>Item 1</li>
</div>

Upvotes: 1

Related Questions