gpt4 book ai didi

python - 搜索并替换 HTML 文本,而不是标签

转载 作者:行者123 更新时间:2023-12-01 05:51:28 25 4
gpt4 key购买 nike

Possible Duplicate:
How to find/replace text in html while preserving html tags/structure

我想通过 HTML 文本进行搜索和替换。我不想摆弄标签或其属性,只想摆弄 HTML 文本。我应该如何在 Python 中做到这一点?

最佳答案

import lxml.etree as et
html=\
"""
<!DOCTYPE html>
<html>
<head>
<title>Hello HTML</title>
</head>
<body>
<p>Hello 1</p>
<p>Hello 2</p>
<p>Hello 3</p>
<p>Hello 4</p>
</body>
</html>
"""
doc = et.fromstring(html)
for i in doc.xpath('.//p[contains(.,"Hello") and not(contains(.,"4"))]'):
i.text='replaced'
print et.tostring(doc,pretty_print=True)

输出:

<html>
<head>
<title>Hello HTML</title>
</head>
<body>
<p>replaced</p>
<p>replaced</p>
<p>replaced</p>
<p>Hello 4</p>
</body>
</html>

关于python - 搜索并替换 HTML 文本,而不是标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14134843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com