Python 如何向BeautifulSoup对象添加外部标记
我正在尝试将iframe的内容替换为BeautifulSoup对象。这么说吧Python 如何向BeautifulSoup对象添加外部标记,python,html,iframe,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> &
s="""
<!DOCTYPE html>
<html>
<body>
<iframe src="http://www.w3schools.com">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
"""
我用f=dom.find('iframe')
现在我只想用另一个BeautifulSoup对象(例如对象newBO)替换iframe的内容。如果我做了f.将_替换为(newBO)
它可以工作,但我丢失了原始文件的层次结构,因为iframe标记不见了。如果我没有一个BeautifulSoup对象,我只有一个字符串,我可以做f.string='just a string'
,这将替换内容,但是如果我做f.string=newBO
我明白了
TypeError:“非类型”对象不可调用
因此,我尝试使用replace_to
,但在newBO中添加iframe
标记。我该怎么做?你能提出其他的建议吗?那么内容是:
这将给你:
<!DOCTYPE html>
<html>
<body>
<iframe src="http://www.w3schools.com"><div>foo</div>
</iframe>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<iframe src="http://www.w3schools.com"><div>foo</div></iframe>
</body>
</html>
福
在这种情况下,您还可以使用
f.append(new)
,因为它将是唯一的元素。您可以使用get_text()
函数返回标记下的内容--f.get_text()。将_替换为(newBO)
。让我知道它是否有效。@NikhilNanjappa,文本与标记无关<代码>获取文本->您的浏览器不支持iframes。因此这不符合OP的要求。您提供的示例很有效,但由于某种原因,当我尝试将其应用于我的问题时,我得到了一些奇怪的结果。我已经在一个字典中存储了一个soup对象,如果我完全按照上面的过程进行操作,但是我没有使用new
而是使用存储在dom字典中的对象,比如f.insert(0,dom[1]
)我得到“NoneType”对象没有属性“insert”
。基本上,f
的每一个函数,我都会用这个参数调用,我会得到这个响应,知道哪里出了问题吗?@LetsPlayYahtzee。该错误源于调用,如f=dom.find('iframe')
返回无,您确定代码正在查找您期望的标记吗?我刚刚意识到它没有找到我要查找的元素,请提供帮助
<!DOCTYPE html>
<html>
<body>
<iframe src="http://www.w3schools.com"><div>foo</div>
</iframe>
</body>
</html>
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>