garmoncheg
garmoncheg

Reputation: 906

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?

Upvotes: 8

Views: 3880

Answers (2)

callmebob
callmebob

Reputation: 6323

In BS4 you can also do this:

img = BeautifulSoup('<img src="/some/url/here" />', 'lxml').img

print(img)
print(type(img))

which will output:

<img src="/some/url/here"/>
<class 'bs4.element.Tag'>

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121844

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>

Upvotes: 12

Related Questions