【问题标题】:How to replace a obsolete font tag with span using Beautiful Soup如何使用 Beautiful Soup 用 span 替换过时的字体标签
【发布时间】:2013-09-26 14:27:43
【问题描述】:

我们需要将 TinyMCE 中生成的过时字体标签迁移到 CMS 中的新跨度标签。

<font face="timesnewroman,times" size="7"><child>something</child></font>

<span style="font-family: timesnewroman,times; font-size: 12pt;"><child>something</child></span>

如何最好使用 BeautifulSoup 来做到这一点? (目前我使用的是 3.2.1 版本) 您能否告诉我 Python 中是否有任何方法可以将字体-> 跨度标记替换为上述样式属性集?我确实知道一些像 replaceWithChildren 这样的方法,但这不会满足我的需要。有什么想法吗 ?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:
    import BeautifulSoup as bp
    
    soup = bp.BeautifulSoup('<font face="timesnewroman,times" size="7"><child>something</child></font>')
    
    
    for t in soup.findAll('font'):
    
        t['style'] = 'font-family: %s; font-size: %s' % (t['face'], t['size'])
    
        del t['face']
        del t['size']
        t.name = 'span'
    
        print t
    

    输出:

    <span style="font-family: timesnewroman,times; font-size: 7"><child>something</child></span>
    

    这是基本思想。显然你应该检查属性是否存在,否则会引发异常。

    【讨论】:

    • 谢谢。正是我想要的,有趣的是它有一个 name 属性。
    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 2017-12-31
    • 2021-01-24
    • 1970-01-01
    • 2018-06-29
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多