BeautifulSoup中的renderContents(Python)

0 投票
1 回答
1698 浏览
提问于 2025-04-16 19:34

我想让下面的代码正常工作:

h = str(heading)
# '<h1>Heading</h1>'
heading.renderContents()

但是我遇到了这个错误:

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print h.renderContents()
AttributeError: 'str' object has no attribute 'renderContents'

有没有什么建议?

我有一个包含HTML标签的字符串,我需要清理它。如果有其他方法可以做到这一点,请告诉我。

1 个回答

1

你的错误信息和代码示例不太一致。你说你在调用:

heading.renderContents()

但是你的错误信息显示你在调用:

print h.renderContents()

这说明你的代码可能有问题,试图在一个字符串对象上调用 renderContents(),而这个字符串并没有这个方法。

无论如何,检查一下 heading 是什么类型的对象会很有帮助,确保它真的是一个 BeautifulSoup 的实例。对于我使用的 BeautifulSoup 3.2.0 版本,这样做是有效的:

from BeautifulSoup import BeautifulSoup
heading = BeautifulSoup('<h1>heading</h1>')
repr(heading)
# '<h1>heading</h1>'
print heading.renderContents()
# <h1>heading</h1>
print str(heading)
# '<h1>heading</h1>'
h = str(heading)
print h
# <h1>heading</h1>

撰写回答