HOWTO · Python
How to Remove HTML Tags From a String in Python
Learn how to extract text from an HTML string in Python with a regular expression, BeautifulSoup, HTMLParser, or ElementTree, and choose the right method for your input.
On this page
To remove HTML tags from a Python string while keeping its text, parse the input and extract its text content. A regular expression can be a quick shortcut for simple, predictable markup; for general HTML, use an HTML parser such as BeautifulSoup or the standard-library HTMLParser. Use ElementTree only when the input is well-formed XML-like markup. Extracting text does not sanitize HTML for safe display in a browser.
Remove HTML Tags With a Regular Expression
A non-greedy pattern such as <.*?> removes text between angle brackets. It is convenient for a small string with simple tags and needs no additional package. Run this example:
import re
html = "<p>This is a <strong>sample</strong> string with <a href='#'>HTML</a> tags.</p>"
text = re.sub(r"<.*?>", "", html)
print(text)
This is a sample string with HTML tags.
This approach treats the input as text, not as an HTML document. It does not understand quoted > characters, comments, scripts, malformed markup, or the meaning of nested elements. Use it only when the input format is controlled and the pattern’s limitations are acceptable.
Remove HTML Tags With BeautifulSoup
BeautifulSoup parses HTML and provides a direct way to collect text from nested elements. It is a third-party package; install beautifulsoup4 in your project environment if it is not already available. The example uses Python’s html.parser backend, so it does not require a separate parser package:
try:
from bs4 import BeautifulSoup
except ImportError:
print("Install beautifulsoup4 to run this example.")
else:
html = "<div>Hello, <b>world</b>! Welcome to <a href='#'>Python</a> programming.</div>"
text = BeautifulSoup(html, "html.parser").get_text()
print(text)
Install beautifulsoup4 to run this example.
When beautifulsoup4 is installed, the success branch prints Hello, world! Welcome to Python programming. The supplied execution evidence covers only the missing-dependency branch shown above, not that success output. get_text() returns text found in the parsed document, without the tags. If you need separators between adjacent text nodes, pass a separator such as a space and decide whether to strip surrounding whitespace. Parser recovery and text formatting can affect the result, so inspect the extracted text when the source has unusual markup.
Remove HTML Tags With HTMLParser
HTMLParser is included with Python and lets you decide what to do with text as the parser encounters it. This subclass appends each data segment, then joins the segments after parsing:
from html.parser import HTMLParser
class TextCollector(HTMLParser):
def __init__(self):
super().__init__()
self.parts = []
def handle_data(self, data):
self.parts.append(data)
html = "<span>Sample text with <em>HTML</em> tags.</span>"
parser = TextCollector()
parser.feed(html)
print("".join(parser.parts))
Sample text with HTML tags.
The handle_data method receives text between markup tokens. Collecting these pieces and joining them avoids repeated string concatenation, but the join inserts no spaces or other separators unless the source contains them or the code explicitly adds them. Add your own handling if you need to ignore the contents of selected elements, preserve whitespace, or insert separators. This parser is useful when you want a standard-library solution with control over text collection, but it does not build a full browser document model.
Remove HTML Tags With ElementTree
ElementTree can extract text from well-formed XML-like input. It is not a general HTML parser: ordinary HTML may omit closing tags or use constructs that XML does not allow. Parse only input that meets XML’s stricter syntax requirements:
import xml.etree.ElementTree as ET
xml = "<root><p>Hello, <b>world</b>!</p></root>"
root = ET.fromstring(xml)
print("".join(root.itertext()))
Hello, world!
itertext() yields the text held by an element and its descendants. Joining those pieces preserves text around nested elements, but does not add spaces that were absent from the source. Malformed XML raises a parse error, so choose an HTML parser for HTML input.
Choose the Right Method
Use a regular expression for a short, controlled string when a simple substitution is sufficient. Choose BeautifulSoup for general HTML when you want a convenient parsing API and can add a dependency. Choose HTMLParser when you prefer the standard library or need to customize how text segments are collected. Choose ElementTree for well-formed XML-like data, not for arbitrary web pages.
These methods do not produce identical formatting. Adjacent text nodes may run together, while spaces and line breaks already present in the source may remain. Decide whether your application needs separators, whitespace normalization, or selective removal of element contents, and handle that explicitly after parsing.
Limitations and Common Pitfalls
Removing tags is different from sanitizing untrusted HTML. Extracted text can still contain entity references, unusual whitespace, or characters that need escaping for the destination format. If the goal is safe browser display, use a context-appropriate escaping or sanitization strategy; stripping tags alone is not a security boundary.
Nested markup is another reason to avoid treating HTML as a regular language with a broad substitution. A regex may appear to work on a sample but remove too much or leave fragments when the markup changes. Parsers handle document structure more appropriately, although malformed input can still be repaired differently by different parsers. Test with representative input and review whether the resulting text preserves the words and spacing your application needs.