首页 > 解决方案 > 如何在 BS4 中添加嵌套的 DIV

问题描述

我想要的只是在我的 HTML 文件中的“容器 DIV”中添加一个 DIV,但 BS4 在该标签之后或之前一直在做!我无法让它进入容器。

这是我的 HTML

<body>
    <div class="container">
        <div class="bg1"><img src="1.png"></div>
        <div class="bg2"><img src="2.png"></div>
    </div>
</body>

这是我的 Python:

with open("/var/www/html/index.html") as inf:
    html = inf.read()
    soup = bs4.BeautifulSoup(html, features="html.parser")
    prettyHTML = soup.prettify()   #prettify the html
    children = soup.div.container
    
addMyDiv= soup.new_tag('div', id='NewDIV') # create the DIV
soup.html.body.insert(1, addMyDiv)

with open("/var/www/html/index.html", "w") as outf:
    outf.write(str(prettyHTML))

它只是在“容器”之后不断添加 DIV 我如何强制它添加到 CONTAINER 内部?

标签: pythonbeautifulsoup

解决方案


推荐阅读