【问题标题】:bs4 : insert new tag in a tag according to a specific attributebs4 : 根据特定属性在标签中插入新标签
【发布时间】:2018-06-06 12:19:21
【问题描述】:

经过一番研究,我找不到足够的解决方案:例如,我想在 'id=2' 时将标签 'b' 插入标签 'a' 中:

<?xml version"1.0 encoding="utf-8?>
<a id=1>
    <a id =2>
    </a>
</a>

我正在考虑类似的事情:soup.a.has_key('2').append(b) 但它不起作用...... 有什么帮助吗?

【问题讨论】:

    标签: python xml python-3.x beautifulsoup


    【解决方案1】:

    也许你可以使用

    from bs4 import BeautifulSoup as bs
    s="""
    <a id=1>
        <a id =2>
        </a>
    </a>
    """
    
    soup = bs(s)
    nt = soup.new_tag('b')
    soup.find(id="2").append(nt)
    

    首先使用new_tag() 创建一个新的&lt;b&gt; 标签,使用find() 找到带有id="2" 的标签,然后用append() 附加新标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 2020-12-20
      • 1970-01-01
      相关资源
      最近更新 更多