Python 脚本,用于将 HTML 文件中的文本替换为用户提供的值



我有一个 hmtl 文件,如下所示:

...
<!-- Special_ID -->
<p> stuff1 </p>
<p> stuff2 </p>
<!-- /Special_ID -->
...

我有一个 INI 文件:

[general]
param=stuff1
 stuff2

如果用户编辑文件并将param值更改为test,我希望将html文件更改为:

...
<!-- Special_ID -->
<p> test </p>
<!-- /Special_ID -->
...

目前,我正在做的是解析INI文件(Python的ConfigParser(,然后将部分("常规"(和选项("参数"(转换为开始和停止的特殊id,如上例所示。

然后:

while we haven't found the start id:
    just write a line to some temporary file
write our start id to the temp file
write out new value ("test") to the temp file # surround with <p>
loop through original file until we find the stop id
then write the stop id and the rest of the file to temp
replace original file with tmp file

有没有更聪明的方法呢?

也许是一个已经这样做的Python模块。

我也不是特别喜欢要求<!-- Special_ID -->,但我没有使用Web框架(只是一个简单的应用程序(,所以我不能像TurboGears那样做一个花哨的<p py:for ...>...

总的来说,

不确定您提出的当前方法,但这里是您如何替换特定注释后的所有p元素并插入新的p元素(使用 HTML 解析器BeautifulSoup(。这个想法是:

  • 在 HTML 中查找注释
  • 遍历所有p同级元素
  • 删除与.extract()找到的每个p元素
  • 使用 .insert_after() 在注释后插入新的p元素

工作代码:

from bs4 import BeautifulSoup, Comment
data = """
<!-- Special_ID -->
<p> stuff1 </p>
<p> stuff2 </p>
<!-- /Special_ID -->
"""
soup = BeautifulSoup(data, "html.parser")
# find "Special_ID" comment
special_id = soup.find(text=lambda text: isinstance(text, Comment) and "Special_ID" in text)
# find all sibling "p" elements
for p in special_id.find_next_siblings("p"):
    p.extract()
# create new "p" element
tag = soup.new_tag("p")
tag.string = "test"
# insert the new "p" element after the comment
special_id.insert_after(tag)
print(soup.prettify())

指纹:

<!-- Special_ID -->
<p>
 test
</p>
<!-- /Special_ID -->

最新更新