Замените класс CSS на HTML-тег

#python #html #css #beautifulsoup

Вопрос:

У меня есть это:

 <span class="ld-nowrap"> 20th century’s </span>
 

и я хочу получить это:

 <em> 20th century’s </em>
 

использование python 3 и BeautifulSoap

Есть какие-нибудь идеи?

Ответ №1:

Вы можете использовать .replace_with() для замены метки внутри супа:

 from bs4 import BeautifulSoup

html_doc = """
<span class="ld-nowrap"> 20th century’s </span>
"""

soup = BeautifulSoup(html_doc, "html.parser")

# 1. find the <span> tag to replace:
span = soup.find("span", class_="ld-nowrap")

# 2. create new <em> tag with the same contents as <span>
em = soup.new_tag("em")
em.contents = span.contents

# 3. replace the tag inside the tree
span.replace_with(em)
print(soup)
 

С принтами:

 
<em> 20th century’s </em>

 

ИЗМЕНИТЬ: Для замены нескольких тегов:

 from bs4 import BeautifulSoup

html_doc = """
<span class="ld-nowrap"> 20th century’s </span>
<span class="ld-nowrap"> 21th century’s </span>
<span> No replace </span>
<span class="ld-nowrap"> 22th century’s </span>
"""

soup = BeautifulSoup(html_doc, "html.parser")

for span in soup.find_all("span", class_="ld-nowrap"):
    em = soup.new_tag("em")
    em.contents = span.contents
    span.replace_with(em)

print(soup)
 

С принтами:

 
<em> 20th century’s </em>
<em> 21th century’s </em>
<span> No replace </span>
<em> 22th century’s </em>

 

Комментарии:

1. Хорошо, но как заменить все теги span? Я имею в виду, если мне нужно использовать find_all span = new_soup.find_all(«span», class_=»ld-nowrap»)

Ответ №2:

Ты имеешь в виду что-то в этом роде?

 soup = '<span class="ld-nowrap"> 20th century’s </span>'

for x in soup.find_all('span', class_= 'ld-nowrap'):
    print('<em>' x.text '</em>')