简体   繁体   中英

BeautifulSoup4: replace a tag with 2 others

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:

  1. wrap the h1 with new tags p
  2. wrap the h1 with new tags u
  3. remove the tag 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM