Beautiful Soup - new_tag() Method



The new_tag() method in Beautiful Soup library creates a new Tag object, that is associated with an existing BeautifulSoup object. You can use this factory method to append or insert the new tag into the document tree.

Syntax

new_tag(name, namespace, nsprefix, attrs, sourceline, sourcepos, **kwattrs)

Parameters

  • name − The name of the new Tag.

  • namespace − The URI of the new Tag's XML namespace, optional.

  • prefix − The prefix for the new Tag's XML namespace, optional.

  • attrs − A dictionary of this Tag's attribute values.

  • sourceline − The line number where this tag was found in its source document.

  • sourcepos − The character position within `sourceline` where this tag was found.

  • kwattrs − Keyword arguments for the new Tag's attribute values.

Return Value

This method returns a new Tag object.

Example 1

The following example shows the use of new_tag() method. A new tag for <a> element. The tag object is initialized with the href and string attributes and then inserted in the document tree.

from bs4 import BeautifulSoup

soup = BeautifulSoup('<p>Welcome to <b>online Tutorial library</b></p>', 'html.parser')
tag = soup.new_tag('a')
tag.attrs['href'] = "www.tutorialspoint.com"
tag.string = "Tutorialspoint"
soup.b.insert_before(tag)
print (soup)

Output

<p>Welcome to <a href="www.tutorialspoint.com">Tutorialspoint</a><b>online Tutorial library</b></p>

Example 2

In the following example, we have a HTML form with two input elements. We create a new input tag and append it to the form tag.

html = '''
   <form>
      <input type = 'text' id = 'nm' name = 'name'>
      <input type = 'text' id = 'age' name = 'age'>
   </form>'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
tag = soup.form
newtag=soup.new_tag('input', attrs={'type':'text', 'id':'marks', 'name':'marks'})
tag.append(newtag)
print (soup)

Output

<form>
<input id="nm" name="name" type="text"/>
<input id="age" name="age" type="text"/>
<input id="marks" name="marks" type="text"/></form>

Example 3

Here we have an empty <p> tag in the HTML string. A new tag is inserted in it.

from bs4 import BeautifulSoup
soup = BeautifulSoup('<p></p>', 'html.parser')
tag = soup.new_tag('b')
tag.string = "Hello World"
soup.p.insert(0,tag)
print (soup)

Output

<p><b>Hello World</b></p>
Advertisements