Tutorial: Building a web corpus#

Get your system up and running#

  1. Installation: see dedicated page

  2. Ensure that you have installed the latest version: pip install -U trafilatura (or pip3)

Note

Most examples below use the command-line; Python alternatives are shown where relevant. See also: Command-line usage, Python usage.

Content discovery#

In order to gather web documents it can be useful to download the portions of a website programmatically, mostly to save time and resources. Trafilatura supports three different ways to gather further links:

  1. Sitemaps: a sitemap is a file that lists the visible URLs for a given site, following the XML format. Sitemaps are particularly useful for large or complex websites where some content may not be reachable through the browsable interface.

  2. Web feeds: a web feed provides users with frequently updated content. Trafilatura supports the two common XML-based formats Atom and RSS.

  3. Web crawling: discovering pages by following links from page to page (see the crawling documentation).

A comprehensive overview of the available documents can be obtained faster and more efficiently using sitemaps and feeds than by systematically crawling. These formats are machine-readable and can reveal content that may not be reachable through the browsable interface. However, link inspection and filtering prior to download is recommended to avoid undesired content — see link filtering below.

In addition, Trafilatura supports multilingual and multinational sitemaps, for example when a site targets different languages through paths like /en/… and /de/….

Hint

Sources can also consist of previously known web pages, lists of links gathered by other projects, or content from Wikipedia and social networks. See the sources page for details.

Multilingual sites#

Trafilatura handles multilingual sitemaps and supports language-based filtering during extraction. To build a corpus from a specific language on a multilingual site:

# discover links — multilingual sitemaps are resolved automatically
$ trafilatura --sitemap "https://www.example.com/" --list > all-links.txt

# extract only German-language pages
$ trafilatura --target-language de -i all-links.txt -o corpus-de/

In Python, use the target_language parameter to discard pages that don’t match:

from trafilatura import fetch_url, extract

html = fetch_url("https://www.example.com/de/artikel")
text = extract(html, target_language="de")  # None if language doesn't match

Language detection relies on the py3langid package (installed with trafilatura) and checks both HTML metadata and the extracted text. Use ISO 639-1 codes (e.g. de, fr, zh).