【问题标题】:Removing span tags in python在python中删除span标签
【发布时间】:2013-06-12 13:44:13
【问题描述】:

我是一个新手,在使用 BeautifulSoup 从页面中抓取 html 后无法删除 span 标签。尝试使用“del links['span'] 但它返回了相同的结果。使用 getText() 的一些尝试也失败了。显然我做错了什么应该很容易。帮助?

from bs4 import BeautifulSoup
import urllib.request
import re
url = urllib.request.urlopen("http://www.python.org")
content = url.read()
soup = BeautifulSoup(content)
for links in soup.find_all("span", text=re.compile(".com")):
    del links['class']
    print(links.)

【问题讨论】:

  • 你想做什么?删除 span tags 或删除 span elements(包括它们的内容)
  • @user1929959 问题的答案没有使用 BeautifulSoup。

标签: python python-3.x


【解决方案1】:

使用.unwrap() method 删除标签,保留其内容:

for links in soup.find_all("span", text=re.compile(".com")):
    links.unwrap()

print soup

【讨论】:

    【解决方案2】:

    根据您要执行的操作,您可以使用unwrap 删除标签(实际上是用其内容替换元素)或decompose 删除元素及其内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-25
      • 2011-02-01
      • 1970-01-01
      • 2017-10-30
      • 2011-05-20
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多