如何在不删除标签的情况下更改 HTML 标签的内部文本
How to change inner text of HTML tags without removing them
假设我有像
这样的“半”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])
感谢您的帮助。谢谢!
保持简单,只需 select 所有文本节点并替换您在示例中已经尝试过的文本:
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
假设我有像
这样的“半”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])
感谢您的帮助。谢谢!
保持简单,只需 select 所有文本节点并替换您在示例中已经尝试过的文本:
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