我的 HTML 代码有 4 个值:h6,h7,h8
和 h9
。我的目标是拥有一个 Python 代码,可以使用 python 代码中的 4 个变量来更新 HTML 中的这些值。类似于(我认为它看起来如何)html.h6 = variable1
。因此,当我刷新本地打开的页面时,新值就在那里。有没有一种简单且有据可查的方法来做到这一点?
最佳答案
您可以使用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
关于python - 使用Python更新HTML文件中4个值的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882363/