<p>您可以使用<code>wrap()</code>方法(<a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#wrap" rel="nofollow noreferrer">doc</a>)将文本包装成<code><span></code>标记-它将更新整个HTML结构</p>
<p>例如:</p>
<pre><code>data = '''<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><link href="style.css" rel="stylesheet" type="text/css" /><title> Name. Of the book. </title></head>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser')
print('Before:')
print('-' * 80)
print(soup.prettify())
print('-' * 80)
for text in soup.find_all(text=True):
text.wrap(soup.new_tag("span")) # use wrap() function to wrap the text into <span> tag
print('After:')
print('-' * 80)
print(soup.prettify())
print('-' * 80)
</code></pre>
<p>打印(注意<code><title></code>标记内的<code><span></code>):</p>
<pre><code>Before:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
<link href="style.css" rel="stylesheet" type="text/css"/>
<title>
Name. Of the book.
</title>
</head>
</html>
After:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
<link href="style.css" rel="stylesheet" type="text/css"/>
<title>
<span>
Name. Of the book.
</span>
</title>
</head>
</html>
</code></pre>