In web scraping and data processing, it is common to come across HTML content which has to be converted to plain text for further analysis. This post shows how to perform this conversion in Python using Trafilatura, the web scraping library I am working on.
Why convert HTML to text?
HTML is the standard markup language for web pages. Besides the text itself, it contains tags, scripts, styles and a series of other elements. Plain text is easier to process, analyze or visualize, so a conversion step is often necessary. There are two main cases:
- Keeping all the text of a page, for example to index it or to search it
- Keeping the main content only, for example to build a text corpus without menus, headers and footers
Getting started
The library can be installed with pip (or pip3 where applicable):
$ pip install trafilatura
For more details please refer to the installation page.
Using the library
The example below downloads a page of this blog and converts it in two different ways:
from trafilatura import fetch_url, html2txt, extract
# download a web page
downloaded = fetch_url("https://adrien.barbaresi.eu/blog/link-filtering-courlan-python.html")
# all the text
full_text = html2txt(downloaded)
# main content only
main_text = extract(downloaded)
The html2txt function returns all the text in the page, starting with the navigation bar:
Toggle navigation Bits of Language: corpus linguistics, NLP and text analytics Corpus Linguistics Tutorials Text Complexity Filtering links to gather texts on the web The issue with URLs and URIs ...
The output also ends with the list of related posts. On the contrary, the extract function focuses on the main content. It starts with the first heading of the post and ends with its last line, while paragraphs are separated by line breaks:
The issue with URLs and URIs
A Uniform Resource Locator (URL), colloquially termed a web address, is a reference to a web resource ...
Since it only strips the markup, html2txt runs almost four times faster on this page. The extract function takes more time but it removes the boilerplate. It can also return other formats such as XML or JSON using the output_format parameter. Comments are included by default, include_comments=False leaves them out.
Summing up
HTML to text conversion is a common task when dealing with web data. Trafilatura offers two functions for it, depending on whether the whole page or only its main content is needed.
For more options please refer to the documentation of the extraction functions.