learner
learner

Reputation: 1051

How to add a new div tag in an existing html file after a h1 tag using python

I have a html file and i want to add a div tag after h1 tag. the div tag will have a anchor tag. how can i edit the existing html file using python and add the div with link this is what i want to do

<h1>
</h1>
<div> <a></a>
</div>

i tried with BeatifulSoup. got AttributeError: 'NoneType' object has no attribute 'insert_after' this error:

htmlFile ='path to html file' 
soup = Soup(htmlFile) 
headTag = soup.find('h1') 
divTag = soup.new_tag('div') 
divTag['class'] = "link" 
headTag.insert_after(divTag)

pls suggest to modify this code to add the div tag in the current html file

Upvotes: 4

Views: 2757

Answers (2)

aIKid
aIKid

Reputation: 28302

The parser fails because you're not passing the content of your file, but instead passing a string of the path. Thus, you are searching for a h1 tag in the path, and the parser wouldn't find it.

htmlFile = open('path to html file').read()

The full code:

with open("path to html file") as file:
    htmlFile = file.read()
    soup = Soup(htmlFile) 
    headTag = soup.find('h1') 
    divTag = soup.new_tag('div') 
    divTag['class'] = "link" 
    headTag.insert_after(divTag)
    print(soup) #This should print the new, modified html

Upvotes: 4

Birei
Birei

Reputation: 36282

Try with append for the <a> tag and insert_after to add it after <h1>:

from bs4 import BeautifulSoup
import sys

soup = BeautifulSoup(open(sys.argv[1], 'r'))
h1 = soup.find('h1')
div = soup.new_tag('div')
a = soup.new_tag('a')
div.append(a)
h1.insert_after(div)

Upvotes: 0

Related Questions