bs4:根据特定属性

时间:2018-06-06 12:19:22

标签: python xml python-3.x beautifulsoup

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

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

我正在思考类似的事情:soup.a.has_key('2').append(b) 但它不起作用...... 一些帮助?

1 个答案:

答案 0 :(得分:0)

也许你可以使用

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)

首先使用<b>创建新的new_tag()标记,找到id="2"的标记find(),新标记附加append()

相关问题