使用BeautifulSoup Python使用冒号删除属性

时间:2019-04-23 09:38:19

标签: python html web-scraping beautifulsoup

我有时会遇到具有奇怪属性的html,例如 fb:share:layout

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

我不确定自己叫什么(itemscopes?命名空间?)。

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

谢谢

编辑: 感谢您的回答。我最终像这样实现它:

    for tag in soup.find_all(True):
            attrs = dict(tag.attrs)
            for attr in attrs:
                if ":" in attr:
                    del tag.attrs[attr]

1 个答案:

答案 0 :(得分:0)

尝试一下。

"require": {
        "composer/installers": "^1.0.24",
        "drupal/auto_entitylabel": "2.x-dev",
        "drupal/signature_field": "^1.0@RC",
        "drupal/eck": "^1.0@alpha",
}

您也可以在下面尝试此操作以获得更多参考。

  

使用BeautifulSoup删除所有HTML属性,除了一些标签(...)

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

我希望它会有所帮助。