【问题标题】:modify style tag python css beautifulsoup修改样式标签 python css beautifulsoup
【发布时间】:2021-04-01 03:52:41
【问题描述】:

给定:

<html>
<style>
@font-face
{font-family:"MS Mincho"}
</style>
</html>

如何将@font-face {font-family:"MS Gothic"} 添加到此样式标签? 我正在使用 Beautiful soup 4 和以下代码来选择样式,但不确定如何在第一个之后添加新样式:

code = BeautifulSoup(html, 'html.parser')
s = code.select('style')

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    要向 HTML 添加新标签,可以使用 .append() 方法:

    您可以使用Tag.append() 添加到标签的内容中。它的工作原理就像在 Python 列表上调用 .append()


    在你的例子中:

    from bs4 import BeautifulSoup
    
    html = """
    <html>
    <style>
    @font-face
    {font-family:"MS Mincho"}
    </style>
    </html>
    """
    soup = BeautifulSoup(html, "html.parser")
    soup.select_one("style").append('@font-face\n{font-family:"MS Gothic"}')
    
    print(soup)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 2021-06-01
      • 1970-01-01
      • 2019-07-17
      • 2016-10-17
      相关资源
      最近更新 更多