embedded
embedded

Reputation: 729

How to add a String into a BeautifulSoup object?

I would like to add this string for example: "{% some_tag dog cat %}" after some HTML element with BeautifulSoap.

I've used something like: elem.insert_after(soup.new_string("{% some_tag dog cat %}")) but this also added </link></meta> tags to the object.

How this can be done properly?

Thanks

Upvotes: 0

Views: 127

Answers (1)

ofrommel
ofrommel

Reputation: 2177

You can use the Python "html.parser" with BeautifulSoup that doesn't try to produce a valid document:

>>> soup = BeautifulSoup('<h1>header</h1>', 'html.parser')
>>> soup
<h1>header</h1>
>>> str = NavigableString("{% some_tag dog cat %}")
>>> soup.append(str)
>>> soup
<h1>header</h1>{% some_tag dog cat %}

see also https://www.crummy.com/software/BeautifulSoup/bs4/doc/#differences-between-parsers

Upvotes: 1

Related Questions