我正在尝试将 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' object is not callable
所以我尝试使用 replace_with
但将 iframe
标记添加到 newBO。我怎样才能做到这一点?你能推荐一些其他的方法吗?
最佳答案
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)
,因为它将成为唯一的元素。
关于python - 如何将外部标签添加到 BeautifulSoup 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39891983/