【问题标题】:Removing span tags from soup BeautifulSoup/Python从汤 BeautifulSoup/Python 中删除 span 标签
【发布时间】:2014-04-25 03:56:40
【问题描述】:

我有一个这样的 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 做到这一点?

【问题讨论】:

  • 试试这个api.jquery.com/unwrap
  • 我不认为这正是我想要的。不过还是谢谢。
  • 好的,请 jsfiddle.net
  • 是的,但我正在尝试在 Python 中执行此操作,因为我是网页抓取。

标签: python html dom beautifulsoup


【解决方案1】:

你会想要使用 beautifulsoup 的 unwrap() 来做这个。

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

【讨论】:

    【解决方案2】:

    您也可以使用replace_with 删除跨度标签:

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

    【讨论】:

      【解决方案3】:

      如果有帮助,我写了这个函数:

      def deleteBalise(string):
          for i in range(2):
              # identifying  <
              rankBegin = 0
              for carac in string:
                  if carac == '<':
                      break
                  rankBegin += 1
              # identifying  >
              rankEnd = 0
              for carac in string:
                  if carac == '>':
                      break
                  rankEnd += 1
              stringToReplace = string[rankBegin:rankEnd+1]
              string = string.replace(stringToReplace,'')
          return string
      

      【讨论】:

      • 宾果游戏!它帮助了我! tnx
      猜你喜欢
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      相关资源
      最近更新 更多