Beautiful Soup 4: Как заменить тег текстом и другим тегом?

Я хочу заменить тег другим тегом и поместить содержимое старого тега перед Новым. Например:

Я хочу изменить это:

<html>
<body>
<p>This is the <span id="1">first</span> paragraph</p>
<p>This is the <span id="2">second</span> paragraph</p>
</body>
</html>

в:

<html>
<body>
<p>This is the first<sup>1</sup> paragraph</p>
<p>This is the second<sup>2</sup> paragraph</p>
</body>
</html>

Я могу легко найти все spans С find_all(), получить номер из атрибута id и заменить один тег на другой тег с помощью replace_with(), но как заменить тег на text и новый тег или вставить текст перед заменил тег?

1 ответов


идея состоит в том, чтобы найти каждый span тег (span[id] селектор CSS), используйте insert_after() вставить sup тег после него и unwrap() чтобы заменить тег на его содержимое:

from bs4 import BeautifulSoup

data = """
<html>
<body>
<p>This is the <span id="1">first</span> paragraph</p>
<p>This is the <span id="2">second</span> paragraph</p>
</body>
</html>
"""

soup = BeautifulSoup(data)
for span in soup.select('span[id]'):
    # insert sup tag after the span
    sup = soup.new_tag('sup')
    sup.string = span['id']
    span.insert_after(sup)

    # replace the span tag with it's contents
    span.unwrap()

print soup

принты:

<html>
<body>
<p>This is the first<sup>1</sup> paragraph</p>
<p>This is the second<sup>2</sup> paragraph</p>
</body>
</html>