使用BeautifulSoup删除所有内联样式

Ila*_*Ila 9 css python inline beautifulsoup

我正在使用BeautifulSoup进行一些HTML清理.Noob同时兼顾Python和BeautifulSoup.根据我在Stackoverflow上的其他地方找到的答案,我按照以下方式正确删除了标签:

[s.extract() for s in soup('script')]
Run Code Online (Sandbox Code Playgroud)

但是如何删除内联样式?例如以下内容:

<p class="author" id="author_id" name="author_name" style="color:red;">Text</p>
<img class="some_image" href="somewhere.com">
Run Code Online (Sandbox Code Playgroud)

应该成为:

<p>Text</p>
<img href="somewhere.com">
Run Code Online (Sandbox Code Playgroud)

如何删除所有元素的内联类,id,名称和样式属性?

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

jmk*_*jmk 26

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

for tag in soup():
    for attribute in ["class", "id", "name", "style"]:
        del tag[attribute]
Run Code Online (Sandbox Code Playgroud)

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

[tag.decompose() for tag in soup("script")]
Run Code Online (Sandbox Code Playgroud)

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


Jon*_*sco 10

我不会这样做BeautifulSoup- 你将花费大量时间来尝试,测试和处理边缘情况.

Bleach为你做这件事. http://pypi.python.org/pypi/bleach

如果您要这样做BeautifulSoup,我建议您采用"白名单"方法,就像这样Bleach做.确定哪些标记可能具有哪些属性,并删除不匹配的每个标记/属性.