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?
-
Look into beautifulsoup, you can load the html, edit it with beautifulsoup and then save the file again. stackoverflow.com/questions/35355225/…MalcolmInTheCenter– MalcolmInTheCenter2017-03-19 02:55:31 +00:00Commented Mar 19, 2017 at 2:55
Add a comment
|
1 Answer
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