您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – BeautifulSoup:剥离指定的属性,但保留标记及其内容

5b51 2022/1/14 8:22:21 python 字数 3073 阅读 549 来源 www.jb51.cc/python

我正在尝试’defrontpagify’MS FrontPage生成的网站的html,我正在写一个BeautifulSoup脚本来做它. 但是,我试图从包含它们的文档中的每个标记中剥离特定属性(或列表属性)的部分.代码段: REMOVE_ATTRIBUTES = ['lang','language','onmouseover','onmouseout','script','style','font

概述

但是,我试图从包含它们的文档中的每个标记中剥离特定属性(或列表属性)的部分.代码段:

REMOVE_ATTRIBUTES = ['lang','language','onmouSEOver','onmouSEOut','script','style','font','dir','face','size','color','class','width','height','hspace','border','valign','align','background','bgcolor','text','link','vlink','alink','cellpadding','cellspacing']

# remove all attributes in REMOVE_ATTRIBUTES from all tags,# but preserve the tag and its content. 
for attribute in REMOVE_ATTRIBUTES:
    for tag in soup.findAll(attribute=True):
        del(tag[attribute])

它运行没有错误,但实际上并没有删除任何属性.当我在没有外部循环的情况下运行它时,只需对单个属性进行硬编码(soup.findAll(‘style’= True),它就可以了.

有人知道这里有问题吗?

PS – 我也不太喜欢嵌套循环.如果有人知道更具功能性的map / filter-ish风格,我很乐意看到它.

for tag in soup.findAll(attribute=True):

没有找到任何标签.可能有一种方法可以使用findAll;我不确定.但是,这有效:

import BeautifulSoup
REMOVE_ATTRIBUTES = [
    'lang','cellspacing']

doc = '''<html><head><title>Page title</title></head><body><p id="firstpara" align="center">This is <i>paragraph</i> <a onmouSEOut="">one</a>.<p id="secondpara" align="blah">This is <i>paragraph</i> <b>two</b>.</html>'''
soup = BeautifulSoup.BeautifulSoup(doc)
for tag in soup.recursiveChildGenerator():
    try:
        tag.attrs = [(key,value) for key,value in tag.attrs
                     if key not in REMOVE_ATTRIBUTES]
    except AttributeError: 
        # 'NavigableString' object has no attribute 'attrs'
        pass
print(soup.prettify())

总结

以上是编程之家为你收集整理的python – BeautifulSoup:剥离指定的属性,但保留标记及其内容全部内容,希望文章能够帮你解决python – BeautifulSoup:剥离指定的属性,但保留标记及其内容所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶