”;
Method Description
The append() method in Beautiful Soup adds a given string or another tag at the end of the current Tag object”s contents. The append() method works similar to the append() method of Python”s list object.
Syntax
append(obj)
Parameters
-
obj − any PageElement, may be a string, a NavigableString object or a Tag object.
Return Type
The append() method doesn”t return a new object.
Example 1
In the following example, the HTML script has a <p> tag. With append(), additional text is appended.In the following example, the HTML script has a <p> tag. With append(), additional text is appended.
from bs4 import BeautifulSoup markup = ''<p>Hello</p>'' soup = BeautifulSoup(markup, ''html.parser'') print (soup) tag = soup.p tag.append(" World") print (soup)
Output
<p>Hello</p> <p>Hello World</p>
Example 2
With the append() method, you can add a new tag at the end of an existing tag. First create a new Tag object with new_tag() method and then pass it to the append() method.
from bs4 import BeautifulSoup, Tag markup = ''<b>Hello</b>'' soup = BeautifulSoup(markup, ''html.parser'') tag = soup.b tag1 = soup.new_tag(''i'') tag1.string = ''World'' tag.append(tag1) print (soup.prettify())
Output
<b> Hello <i> World </i> </b>
Example 3
If you have to add a string to the document, you can append a NavigableString object.
from bs4 import BeautifulSoup, NavigableString markup = ''<b>Hello</b>'' soup = BeautifulSoup(markup, ''html.parser'') tag = soup.b new_string = NavigableString(" World") tag.append(new_string) print (soup.prettify())
Output
<b> Hello World </b>
”;