使用BeautifulSoup Python删除带有冒号的属性

2024-06-17 18:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有时会遇到带有奇怪属性的html,例如fb:共享:布局。在

<a class="addthis_button_facebook_share" fb:share:layout="button_count" style="height:20px;"></a>

我不完全确定它们叫什么(itemscopes?命名空间?)。在

目前我用python中的beautifulsoup4解析HTML。我想知道是否有一种方法可以删除或重命名包含这些冒号的所有属性。在

谢谢

编辑: 谢谢你的回答。我最后是这样实施的:

^{pr2}$

Tags: sharefacebookfb属性stylehtmlcountbutton
1条回答
网友
1楼 · 发布于 2024-06-17 18:32:21

试试这个。在

from BeautifulSoup import BeautifulSoup

def _remove_attrs(soup):
    tag_list = soup.findAll(lambda tag: len(tag.attrs) > 0)
    for t in tag_list:
        for attr, val in t.attrs:
            del t[attr]
    return soup


def example():
    doc = '<html><head><title>test</title></head><body id="foo"><p class="whatever">junk</p><div style="background: yellow;">blah</div></body></html>'
    print 'Before:\n%s' % doc
    soup = BeautifulSoup(doc)
    clean_soup = _remove_attrs(soup)
    print 'After:\n%s' % clean_soup

你也可以试试下面的额外参考。在

Remove all HTML attributes with BeautifulSoup except some tags( ...)

^{pr2}$

我希望有帮助。在

相关问题 更多 >