Jamal
Jamal

Reputation: 387

How to add a Tag (which is in the form of a string) to a soup in BeautifulSoup

I have a Tag which is available to me as a string only. Example: tag_str = 'hello'

When I do the following:

template_logo_h1_tag.insert(0, tag_str)

Where template_logo_h1_tag is a h1 tag

the resulting template_logo_h1_tag is

<h1 id="logo">&lt;a&gt;hello&lt;/a&gt;</h1>

I want to avoid this HTML escaping and the resulting tag to be

<h1 id="logo"><a>hello</a></h1>

Is there anything I am missing? I tried BeautifulSoup.HTML_ENTITIES but this to unescape already "html-escaped" strings. It would be great if you could help me out!

Upvotes: 0

Views: 416

Answers (2)

Anov
Anov

Reputation: 2321

I think you are looking for Beautiful Soup's .append method: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#append

Coupled with the factory method for creating a new tag: soup.new_tag()

Updating with code:

soup=BeautifulSoup('<h1 id="logo"></h1>')
template_logo_h1_tag=soup.h1
newtag=soup.new_tag("a")
newtag.append("hello")
template_logo_h1_tag.append(newtag)

Then

print soup.prettify

yields

<h1 id="logo">
 <a>
  hello
 </a>
</h1>

Upvotes: 1

Jamal
Jamal

Reputation: 387

I found a dirty hack:

template_logo_h1_tag.insert(0, BeautifulSoup('hello').a)

Upvotes: 1

Related Questions