【问题标题】:Update the values of 4 values in a HTML file using Python使用 Python 更新 HTML 文件中 4 个值的值
【发布时间】:2017-08-10 11:27:39
【问题描述】:

我的 HTML 代码有 4 个值,h6,h7,h8h9。我的目标是拥有一个 Python 代码,它使用 Python 代码中的 4 个变量来更新 HTML 中的这些值。类似于(我认为它看起来如何)html.h6 = variable1。所以当我刷新本地打开的页面时,新值就在那里。有没有一种简单且有据可查的方法来做到这一点?

【问题讨论】:

标签: python html web


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多