从汤BeautifulSoup / Python中删除span标签

时间:2014-03-19 05:14:01

标签: python html dom beautifulsoup

我在Python中有这样的汤:

<p>
 <span style="text-decoration: underline; color: #3366ff;">
   Title:
 </span>
 Info
</p>
<p>
 <span style="color: #3366ff;">
  <span style="text-decoration: underline;">
   Title2:
  </span>
 </span>
 Info2
</p>

我想让它看起来像这样:

<p>
   Title:
 Info
</p>
<p>
   Title2:
 Info2
</p>

有没有办法用bs4做到这一点?

3 个答案:

答案 0 :(得分:15)

你会想要使用beautifulsoup的unwrap()

import bs4
soup1 = bs4.BeautifulSoup(htm1, 'html.parser')
for match in soup1.findAll('span'):
    match.unwrap()
print soup1

答案 1 :(得分:3)

您还可以使用replace_with删除范围代码:

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
for span_tag in soup.findAll('span'):
    span_tag.replace_with('')
print(soup)

答案 2 :(得分:0)

我写了这个函数是否可以帮助您

sudo apt update
sudo apt-get install php8.0-soap