It is often possible to extract the title of an HTML document with a regular expression in Python. A pattern specifies the surrounding tags, and a group captures the text.
Though it does not always work, due to comments and other issues, the re.match
method is worth a try on HTML. The total program size is kept small and no complex parser is needed.
This Python program introduces the gettitle()
method, which receives an HTML string
and returns the title. We begin by specifying the HTML as a string
.
string
is "Example" and this is our desired result.re.match
. We must use a pattern that matches the entire string
, so we allow leading and trailing chars around the tags.Match
against None
, and then return the first group (which was captured by the parentheses).import re def gettitle(html): # Part 2: use re.match to match the entire html string, and extract data within the title. m = re.match(r"^.*<title>\s*(.+?)\s*</title>.*$", html) # Part 3: return the first group if match was successful. if m: return m.group(1) return "" # Part 1: specify html string and get its title. html = r"<html><title>Example.</title><body><p>...</p></body></html>" print("TITLE:", gettitle(html))TITLE: Example.
In HTML, titles often contain important information about pages. And with Python we are often tasked with processing data files (which might involve their titles).
HTML can often be invalid, or may contain commented-out HTML. This is difficult for re.match
to deal with—but often it has enough power to capture text.