2

I have a HTML code that has 4 values, h6,h7,h8 and h9. My goal is to have a Python code that updates those values in the HTML using 4 variables in the python code. Something like (how I think it would look) html.h6 = variable1. So when I refresh the page opened locally, the new values are there. Is there a easy and well documented way to do this?

1

1 Answer 1

3

You can use BeautifulSoup:

from bs4 import BeautifulSoup

html = '''
<html><body>
<h6>variable 1</h6>
<h8>variable 3</h8>  
</body></html>
'''
soup = BeautifulSoup(html, 'html.parser')

h6 = soup.find_all('h6') # all elements that match your filters
h8 = soup.find('h8') # return one element

# replace all h6 tags string it with the the string of your choice:
for tag in h6:
    tag.string.replace_with('new variable value')

h8.string.replace_with('new text')

print str(soup)

#Output
<html><body>
<h6>new variable value</h6>
<h8>new text</h8>
</body></html>py
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.