How to get HTML from a beautiful soup object

PythonHtmlBeautifulsoupHtml Parsing

Python Problem Overview


I have the following bs4 object listing:

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


>>> type(listing)
<class 'bs4.element.Tag'>

I want to extract the raw html as a string. I've tried:

>>> a = listing.contents
>>> type(a)
<type 'list'>

So this does not work. How can I do this?

Python Solutions


Solution 1 - Python

Just get the string representation:

html_content = str(listing)

This is a non-prettified version.

If you want a prettified one, use prettify() method:

html_content = listing.prettify()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1592380View Question on Stackoverflow
Solution 1 - PythonalecxeView Answer on Stackoverflow