我有一个HTML代码,它有4个值,h6,h7,h8和h9。我的目标是拥有一个Python代码,使用python代码中的4个变量更新HTML中的这些值。类似于(我认为它会是什么样的) html.h6 = variable1。因此,当我刷新本地打开的页面时,就会出现新的值。是否有一种简单而有详细记录的方法来做到这一点?
发布于 2017-03-19 04:37:49
您可以使用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>pyhttps://stackoverflow.com/questions/42882363
复制相似问题