<p>您可以使用<code>for</code>-loop处理<code>source</code>中的所有子项。<br/>
你可以用<code>copy.copy(child)</code>和<code>append</code>到<code>target</code>复制它们。<br/>
同时,您可以检查<code>child</code>是否为<code>NavigableString</code>并将其转换</p>
<hr/>
<pre><code>text = '''<source><x ctype="x-htmltag" equiv-text="&lt;b&gt;" id="html_tag_191"/>Choose your product\
<x ctype="x-htmltag" equiv-text="&lt;/b&gt;" id="html_tag_192"/>From a list: </source>'''
conversions = {
'Choose your product': 'Wybierz swój produkt',
'From a list: ': 'Z listy: ',
}
from bs4 import BeautifulSoup as BS
from bs4.element import NavigableString
import copy
#soup = BS(text, 'html.parser') # it has problem to parse it
#soup = BS(text, 'html5lib') # it has problem to parse it
soup = BS(text, 'lxml')
# create `<target>`
target = soup.new_tag('target')
# add `<target>` after `<source>
source = soup.find('source')
source.insert_after('', target)
# work with children in `<source>`
for child in source:
print('type:', type(child))
# duplicate child and add to `<target>`
child = copy.copy(child)
target.append(child)
# convert text and replace in child in `<target>`
if isinstance(child, NavigableString):
new_text = conversions[child.string]
child.string.replace_with(new_text)
print(' - target -')
print(target)
print(' - source -')
print(source)
print(' - soup -')
print(soup)
</code></pre>
<p>结果(为使其更具可读性,几乎没有重新格式化):</p>
<pre><code>type: <class 'bs4.element.Tag'>
type: <class 'bs4.element.NavigableString'>
type: <class 'bs4.element.Tag'>
type: <class 'bs4.element.NavigableString'>
- target -
<target>
<x ctype="x-htmltag" equiv-text="&lt;b&gt;" id="html_tag_191"></x>
Wybierz swój produkt
<x ctype="x-htmltag" equiv-text="&lt;/b&gt;" id="html_tag_192"></x>
Z listy:
</target>
- source -
<source>
<x ctype="x-htmltag" equiv-text="&lt;b&gt;" id="html_tag_191"></x>
Choose your product
<x ctype="x-htmltag" equiv-text="&lt;/b&gt;" id="html_tag_192"></x>
From a list:
</source>
- soup -
<html><body>
<source>
<x ctype="x-htmltag" equiv-text="&lt;b&gt;" id="html_tag_191"></x>
Choose your product
<x ctype="x-htmltag" equiv-text="&lt;/b&gt;" id="html_tag_192"></x>
From a list:
</source>
<target>
<x ctype="x-htmltag" equiv-text="&lt;b&gt;" id="html_tag_191"></x>
Wybierz swój produkt
<x ctype="x-htmltag" equiv-text="&lt;/b&gt;" id="html_tag_192"></x>
Z listy:
</target>
</body></html>
</code></pre>