【问题标题】:Remove all inline styles using BeautifulSoup使用 BeautifulSoup 删除所有内联样式
【发布时间】:2012-10-09 04:27:59
【问题描述】:

我正在使用 BeautifulSoup 进行一些 HTML 清理。 Python 和 BeautifulSoup 的新手。根据我在 Stackoverflow 其他地方找到的答案,我已经正确删除了如下标签:

[s.extract() for s in soup('script')]

但是如何删除内联样式呢?例如:

<p class="author" id="author_id" name="author_name" style="color:red;">Text</p>
<img class="some_image" href="somewhere.com">

应该变成:

<p>Text</p>
<img href="somewhere.com">

如何删除所有元素的内联class、id、name&style属性?

我可以找到其他类似问题的答案,我可以找到所有提到的使用 CSS 解析器来处理这个问题,而不是 BeautifulSoup,但由于任务只是删除而不是操纵属性,并且是所有标签的一揽子规则,我是希望能在 BeautifulSoup 中找到一种方法。

【问题讨论】:

    标签: python css beautifulsoup inline


    【解决方案1】:

    如果您只想删除所有 CSS,则无需解析任何 CSS。 BeautifulSoup 提供了一种删除整个属性的方法,如下所示:

    for tag in soup():
        for attribute in ["class", "id", "name", "style"]:
            del tag[attribute]
    

    此外,如果您只想删除整个标签(及其内容),则不需要返回标签的extract()。你只需要decompose():

    [tag.decompose() for tag in soup("script")]
    

    差别不大,只是我在查看文档时发现的其他内容。您可以在BeautifulSoup documentation 中找到有关 API 的更多详细信息,其中包含许多示例。

    【讨论】:

    • 我使用 extract() 以防我决定在任何时候生成已删除代码的列表,但 decompose() 也适用于完全删除和销毁标签和内容。感谢您的属性删除 sn-p,就像一个魅力!
    • 有道理。我会把关于decompose() 的注释留给任何可能偶然发现的人。
    【解决方案2】:

    我不会在 BeautifulSoup 中这样做 - 你会花费大量时间尝试、测试和解决边缘情况。

    Bleach 正是为您做这件事。 http://pypi.python.org/pypi/bleach

    如果您要在 BeautifulSoup 中执行此操作,我建议您使用“白名单”方法,就像 Bleach 一样。确定哪些标签可能具有哪些属性,并删除每个不匹配的标签/属性。

    【讨论】:

    • 酷,我不知道漂白剂。我没有考虑用例,但如果目标是清理不受信任的 HTML,那么这绝对是一种更好的方法。你得到我的支持!
    • 漂白剂非常棒。我真的很喜欢。
    【解决方案3】:

    这是我针对 Python3 和 BeautifulSoup4 的解决方案:

    def remove_attrs(soup, whitelist=tuple()):
        for tag in soup.findAll(True):
            for attr in [attr for attr in tag.attrs if attr not in whitelist]:
                del tag[attr]
        return soup
    

    它支持应保留的属性白名单。 :) 如果没有提供白名单,则所有属性都将被删除。

    【讨论】:

      【解决方案4】:

      基于jmk的功能,我使用这个功能来删除基于白名单的属性:

      在 python2、BeautifulSoup3 中工作

      def clean(tag,whitelist=[]):
          tag.attrs = None
          for e in tag.findAll(True):
              for attribute in e.attrs:
                  if attribute[0] not in whitelist:
                      del e[attribute[0]]
              #e.attrs = None     #delte all attributes
          return tag
      
      #example to keep only title and href
      clean(soup,["title","href"])
      

      【讨论】:

      • 您不应该将可变结构作为默认函数参数值传递。如所见here.
      【解决方案5】:

      不完美但很短:

      ' '.join([el.text for tag in soup for el in tag.findAllNext(whitelist)]);
      

      【讨论】:

        【解决方案6】:

        lxml 的 Cleaner 呢?

        from lxml.html.clean import Cleaner
        
        content_without_styles = Cleaner(style=True).clean_html(content)
        

        【讨论】:

          猜你喜欢
          • 2013-01-05
          • 1970-01-01
          • 2012-07-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-30
          • 2014-03-15
          • 1970-01-01
          相关资源
          最近更新 更多