假设我有一个包含div的页面。我可以用soup.find()很容易地得到那个div。
现在我有了结果,我想打印出div的整个innerhtml:我的意思是,我需要一个包含所有div标签和文本的字符串,就像我用obj.innerHTML在javascript中得到的字符串一样。这个是可能的吗?
发布于 2013-09-04 06:04:32
TL;DR
对于UTF4,如果您想要一个BeautifulSoup -8编码的字节字符串,请使用element.encode_contents();如果您想要一个Python Unicode字符串,请使用element.decode_contents()。例如,DOM's innerHTML method可能如下所示:
def innerHTML(element):
"""Returns the inner HTML of an element as a UTF-8 encoded bytestring"""
return element.encode_contents()这些函数目前不在在线文档中,因此我将引用代码中的当前函数定义和文档字符串。
encode_contents -从4.0.4开始
def encode_contents(
self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING,
formatter="minimal"):
"""Renders the contents of this tag as a bytestring.
:param indent_level: Each line of the rendering will be
indented this many spaces.
:param encoding: The bytestring will be in this encoding.
:param formatter: The output formatter responsible for converting
entities to Unicode characters.
"""另请参阅documentation on formatters;除非您想以某种方式手动处理文本,否则很可能使用formatter="minimal" (缺省设置)或formatter="html" (用于html entities)。
encode_contents返回一个编码的字节串。如果需要Python Unicode字符串,请使用decode_contents。
decode_contents -从4.0.1开始
decode_contents的作用与encode_contents相同,但返回的是Python Unicode字符串,而不是编码的字节字符串。
def decode_contents(self, indent_level=None,
eventual_encoding=DEFAULT_OUTPUT_ENCODING,
formatter="minimal"):
"""Renders the contents of this tag as a Unicode string.
:param indent_level: Each line of the rendering will be
indented this many spaces.
:param eventual_encoding: The tag is destined to be
encoded into this encoding. This method is _not_
responsible for performing that encoding. This information
is passed in so that it can be substituted in if the
document contains a <META> tag that mentions the document's
encoding.
:param formatter: The output formatter responsible for converting
entities to Unicode characters.
"""BeautifulSoup 3
BeautifulSoup 3没有上述功能,而是具有renderContents
def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Renders the contents of this tag as a string in the given
encoding. If encoding is None, returns a Unicode string.."""为了与BS3兼容,在BeautifulSoup 4 (in 4.0.4)中重新添加了此函数。
发布于 2011-11-14 00:39:31
其中一个选项可以使用类似这样的内容:
innerhtml = "".join([str(x) for x in div_element.contents]) 发布于 2017-11-18 18:21:16
如果您只需要文本(不需要HTML标记),那么可以使用.text
soup.select("div").texthttps://stackoverflow.com/questions/8112922
复制相似问题