Add meta tag using BeautifulSoup

beautifulsoup, python, python-2.7

Solution

Use `soup.create_tag()` to create a new `<meta>` tag, set attributes on that and add it to your document `<head>`.

metatag = soup.new_tag('meta')
metatag.attrs['http-equiv'] = 'Content-Type'
metatag.attrs['content'] = 'text/html'
soup.head.append(metatag)

Demo:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <html><head><title>Hello World!</title>
... </head><body>Foo bar</body></html>
... ''')
>>> metatag = soup.new_tag('meta')
>>> metatag.attrs['http-equiv'] = 'Content-Type'
>>> metatag.attrs['content'] = 'text/html'
>>> soup.head.append(metatag)
>>> print soup.prettify()
<html>
 <head>
  <title>
   Hello World!
  </title>
  <meta content="text/html" http-equiv="Content-Type"/>
 </head>
 <body>
  Foo bar
 </body>
</html>

Problem

How to add a meta tag just after title tag in a HTML page by using Beautiful Soup(library). I am using python language for coding and unable to do this.

Original source