如何更改 HTML 标签的内部文本而不删除它们
假设我有“半”HMTL 字符串,比如
some_string = "sometext<body>someText<h1>Text</h1>Worldt<p>And some text here<br>Text.</p></body>HereAlsoText"
我需要替换字符串中的所有标签,但保留所有 HTML 标签(包括 br):
"UPDATED<body>UPDATED<h1>UPDATED</h1>UPDATED<p>UPDATED<br>UPDATED</p></body>UPDATED"
以下代码可以工作,但无法使用
执行任何操作html 之前和之后的标签和文本(在本例中,在 body
标签之外):
soup = BeautifulSoup(mod_string, "html.parser")
# Find all tags
tags = soup.find_all()
# Loop through child tags
for tag in tags:
# Check if tag is a string
if tag.string:
if tag.name != 'br':
# Replace string
tag.string.replace_with("TEST")
for parent_tag in tags:
if not parent_tag.string:
parent_tag.string = ''.join(
["TEST"
if not re.match(r'<[^>]+>', str(t)) else str(t)
for t in parent_tag.contents])
感谢您的帮助。谢谢!
Assuming I have "semi" HMTL string like
some_string = "sometext<body>someText<h1>Text</h1>Worldt<p>And some text here<br>Text.</p></body>HereAlsoText"
I need to replace all tags in the string but with keeping all HTML tags (including br):
"UPDATED<body>UPDATED<h1>UPDATED</h1>UPDATED<p>UPDATED<br>UPDATED</p></body>UPDATED"
The following code works, but cannot do anything with <br>
tag and text before and after html (outside of body
tag, in this case):
soup = BeautifulSoup(mod_string, "html.parser")
# Find all tags
tags = soup.find_all()
# Loop through child tags
for tag in tags:
# Check if tag is a string
if tag.string:
if tag.name != 'br':
# Replace string
tag.string.replace_with("TEST")
for parent_tag in tags:
if not parent_tag.string:
parent_tag.string = ''.join(
["TEST"
if not re.match(r'<[^>]+>', str(t)) else str(t)
for t in parent_tag.contents])
Appreciate your help. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
保持更简单,只需选择所有文本节点并替换您在示例中已经尝试过的文本:
示例
输出
Keep it more simple, just select all the text nodes and replace the text as you have already tried in your example:
Example
Output