Search code examples
pythonhtmlparsingtagsbeautifulsoup

BeautifulSoup create a <img /> tag


I need to create a <img /> tag. BeautifulSoup creates an image tag like this with code I did:

soup = BeautifulSoup(text, "html5")
tag = Tag(soup, name='img')
tag.attrs = {'src': '/some/url/here'}
text = soup.renderContents()
print text

Output: <img src="/some/url/here"></img>

How to make it? : <img src="/some/url/here" />

It can be of course done with REGEX or similar chemistry. However I was wondering maybe there is any standard way to produce tags like this?


Solution

  • Don't use Tag() to create new elements. Use the soup.new_tag() method:

    soup = BeautifulSoup(text, "html5")
    new_tag = soup.new_tag('img', src='/some/url/here')
    some_element.append(new_tag)
    

    The soup.new_tag() method will pass along the correct builder to the Tag() object, and it is the builder that is responsible for recognising <img/> as an empty tag.

    Demo:

    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup('<div></div>', "html5")
    >>> new_tag = soup.new_tag('img', src='/some/url/here')
    >>> new_tag
    <img src="/some/url/here"/>
    >>> soup.div.append(new_tag)
    >>> print soup.prettify()
    <html>
     <head>
     </head>
     <body>
      <div>
       <img src="/some/url/here"/>
      </div>
     </body>
    </html>