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

标签 python html iframe beautifulsoup

我正在尝试将 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。我怎样才能做到这一点?你能推荐一些其他的方法吗?

最佳答案

extract然后是内容insert :

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/

相关文章:

python - 使用 Python 运行 openalpr

python - 列表对象转换为整数

html - 如何在图像链接中环绕文本? HTML CSS

angular - 在 Angular 火灾、不安全值、domsanitation中基于数据库查询动态显示iframe

javascript - 如何使用 jquery 将 iframe 添加到 div

python - 如何从数据框中选择给定列中的值不为 None 的行?

python - 用 pandas 将一年中的一周解析为日期时间对象

javascript - 在 JavaScript 中通过 ADODB 从 Access DB 构建 HTML 表

javascript - 响应式网格问题

jquery - 使用 jQuery 将高度设置为 iframe 后滚动问题