![]() |
VOOZH | about |
Prerequisites: BeautifulSoup
Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to modify the parse tree. BeautifulSoup is used to search the parse tree and allow you to modify the tree. You can rename tag, change the values of its attributes, add and delete attribute.
You can change the name of the tag and modify its attribute by adding or deleting them.
Syntax: tag.name = "new_tag"
Syntax: tag["attribute"] = "value"
Syntax: del tag["attribute"]
A tree can also be modified by inserting new elements at required places.
Syntax: tag.insert()
Syntax: tag.insert_after()
Syntax: tag.insert_before()
Approach :
Example 1:
Output:
👁 ImageExample 2:
Output:
👁 modify tree python bs4The tree can be modified by adding a new tag at any required location. We can also wrap the element to modify it.
Syntax: new_tag("attribute")
Syntax: wrap()
Syntax: unwrap()
Example:
Output:
👁 Imagereplace_with() function will replace old tag or string with new tag or string in the parse tree.
Syntax: replace_with()
Example:
Output:
<a href="https://www.gfg.com//">Geeks for Geeks <p>gfg.in</p></a>
For adding new contents to an existing tag can be done by append() function or NavigableString() constructor.
Syntax: tag.append("content")
Example:
Output:
<a href="https://www.geeksforgeeks.org/">Geeks for Geeks| A Computer Science portal</a>
<a href="https://www.geeksforgeeks.org/">Geeks for Geeks| A Computer Science portal for geeks</a>
A tree can be modified by removing content from it or by removing element also.
Syntax: clear()
Syntax: extract()
Syntax: decompose()
Example: