如何在不删除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"

以下代码可以工作,但不能对<br>标记和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])

感谢你的帮助。谢谢

保持简单,只需选择所有文本节点并替换文本,就像您在示例中已经尝试过的那样:

for e in soup.find_all(text=True):
e.string.replace_with('UPDATE')

示例

import requests
from bs4 import BeautifulSoup
some_string = 'sometext<body>someText<h1>Text</h1>Worldt<p>And some text here<br>Text.</p></body>HereAlsoText'
soup = BeautifulSoup(some_string, 'html.parser')
for e in soup.find_all(text=True):
e.string.replace_with('UPDATE')
print(soup)

输出

UPDATE<body>UPDATE<h1>UPDATE</h1>UPDATE<p>UPDATE<br/>UPDATE</p></body>UPDATE

相关内容

最新更新