I want to replace <h1>title</h1>
with <b><u>title</u></b>
I know I can replace h1
with b
using soup.h1.name = "b"
But is there a way to replace a single tag by several others?
(Special edit for Daniel Roseman: the tags don't really matter... )
Use wrap()
From the documentation:
soup = BeautifulSoup("<p>I wish I was bold.</p>")
soup.p.string.wrap(soup.new_tag("b"))
# <b>I wish I was bold.</b>
soup.p.wrap(soup.new_tag("div"))
# <div><p><b>I wish I was bold.</b></p></div>
thanks to RobertB I could figure out the rest of the answser.
You need:
h1
with new tags p
h1
with new tags u
h1
(using unwrap()
) <!-- language: python -->
from bs4 import BeautifulSoup
soup = BeautifulSoup("<h1>title</h1>", "html.parser")
soup.h1.string.wrap(soup.new_tag("b"))
print(soup) # >> <h1><b>title</b></h1>
soup.h1.string.wrap(soup.new_tag("u"))
print(soup) # >> <h1><b><u>title</u></b></h1>
soup.h1.unwrap()
print(soup) #>> <b><u>title</u></b>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.