Python: of to get the HTML contents of an element with BeautifulSoup

In this article we will see how to get the HTML contents of an element with BeautifulSoup in Python.

We can use the encode_contents() method which returns a sequence of bytes which we can convert to string with the decode() method.

def bs_innerhtml(bs_element=None):
    if bs_element is None:
        return None
    html_bytes = bs_element.encode_contents()
    return html_bytes.decode()    
Back to top