繁体   English   中英

如何将外部标签添加到 BeautifulSoup 对象

[英]How to add outer tag to BeautifulSoup object

我正在尝试将 iframe 的内容替换为 BeautifulSoup 对象。 说这个

 s="""
 <!DOCTYPE html>
 <html>
 <body>

 <iframe src="http://www.w3schools.com">         
   <p>Your browser does not support iframes.</p>
 </iframe>

 </body>
 </html>
 """

是被解析的原始 html

dom = BeatifulSoup(s, 'html.parser')

我用f = dom.find('iframe')得到 iframe

现在我只想用另一个 BeautifulSoup 对象替换 iframe 的内容,例如对象 newBO。 如果我执行f.replace_with(newBO)它可以工作,但由于 iframe 标签消失了,我失去了原始文件的层次结构。 如果我只有一个字符串而不是 BeautifulSoup 对象,我可以执行f.string = 'just a string'并且这将替换内容,但是如果我执行f.string = newBO

我得到

TypeError: 'NoneType' 对象不可调用

所以我试图使用replace_with但向 newBO 添加iframe标签。 我怎样才能做到这一点? 你能建议一些其他的方式吗?

提取内容然后 插入

from bs4 import BeautifulSoup
dom = BeautifulSoup(s, 'html.parser')

f = dom.find('iframe')
for ele in f.find_all():
    ele.extract()
new = BeautifulSoup("<div>foo</div>").find("div")
f.insert(0, new)
print(dom)

这会给你:

 <!DOCTYPE html>

<html>
<body>
<iframe src="http://www.w3schools.com"><div>foo</div>

</iframe>
</body>
</html>

还要删除任何字符串集f.string=""

f = dom.find('iframe')

for ele in f.find_all():
    print(type(ele))
    ele.extract()
f.string = ""
new = BeautifulSoup("<div>foo</div>","html.parser").find("div")
f.insert(0, new)
print(dom)

然后会给你:

<!DOCTYPE html>

<html>
<body>
<iframe src="http://www.w3schools.com"><div>foo</div></iframe>
</body>
</html>

在这种情况下,您也可以使用f.append(new)因为它将成为唯一的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM