Can I remove script tags with BeautifulSoup?

PythonHtmlBeautifulsoup

Python Problem Overview


Can <script> tags and all of their contents be removed from HTML with BeautifulSoup, or do I have to use Regular Expressions or something else?

Python Solutions


Solution 1 - Python

from bs4 import BeautifulSoup
soup = BeautifulSoup('<script>a</script>baba<script>b</script>', 'html.parser')
for s in soup.select('script'):
    s.extract()
print(soup)
baba

Solution 2 - Python

Updated answer for those who might need for future reference: The correct answer is. decompose(). You can use different ways but decompose works in place.

Example usage:

soup = BeautifulSoup('<p>This is a slimy text and <i> I am slimer</i></p>')
soup.i.decompose()
print str(soup)
#prints '<p>This is a slimy text and</p>'

Pretty useful to get rid of detritus like <script>, <img> and so forth.

Solution 3 - Python

As stated in the (official documentation) you can use the extract method to remove all the subtree that matches the search.

import BeautifulSoup
a = BeautifulSoup.BeautifulSoup("<html><body><script>aaa</script></body></html>")
[x.extract() for x in a.findAll('script')]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - PythonFábio DinizView Answer on Stackoverflow
Solution 2 - PythonAbhishek DujariView Answer on Stackoverflow
Solution 3 - PythonSantiago AlessandriView Answer on Stackoverflow