如何从美丽的汤对象中获取HTML

use*_*629 49 html python beautifulsoup html-parsing

我有以下bs4对象列表:

>>> listing
<div class="listingHeader">
<h2>
....


>>> type(listing)
<class 'bs4.element.Tag'>
Run Code Online (Sandbox Code Playgroud)

我想将原始html提取为字符串.我试过了:

>>> a = listing.contents
>>> type(a)
<type 'list'>
Run Code Online (Sandbox Code Playgroud)

所以这不起作用.我怎样才能做到这一点?

ale*_*cxe 92

只需获取字符串表示:

html_content = str(listing)
Run Code Online (Sandbox Code Playgroud)

这是一个非美化版本.

如果你想要一个美化的,使用prettify()方法:

html_content = listing.prettify()
Run Code Online (Sandbox Code Playgroud)

  • 我一直在为变音 ä,ö,ü 等特殊字符而苦苦挣扎。人们可能想使用`soup.prettify( formatter="html" )` - 比较https://www.crummy.com/software/BeautifulSoup/bs4/doc/#output-formatters (3认同)
  • @ user61629呀,你可以用`unicode(listing)`. (2认同)