As natural language processing and linguistic analysis scale up, data preprocessing becomes an ever more relevant step. Many tools are available to scrape and process web pages but most of them are geared towards general use. The web scraping library I am working on, Trafilatura, is designed with text analysis in mind: it can navigate sitemaps, download pages and extract their main text in a series of formats.

This tutorial shows how to build a small corpus out of a website in a few functions. The script lists the pages of a website, keeps those matching a keyword, then extracts their main text and stores each one in a text file. It is geared towards beginner to intermediate Python developers.

Project description

The example consists of building a corpus of soup recipes. It uses Public Domain Recipes, a small community website whose contents are in the public domain, which makes it a good candidate for a corpus.

The library can be installed with pip (or pip3 where applicable), ideally in a virtual environment:

$ pip install trafilatura

For more details please refer to the installation page.

The script is written in a file called corpus_manager.py. It starts with the necessary imports:

import time
from pathlib import Path

from trafilatura import extract, fetch_url
from trafilatura.sitemaps import sitemap_search

Managing file paths

The first function is a utility. It creates a corpus directory within a main directory (for a series of corpora) and returns its path. Existing directories are left untouched:

def file_path_manager(corpora_dir, corpus_dir):
    path = Path.cwd() / corpora_dir / corpus_dir
    path.mkdir(parents=True, exist_ok=True)
    return path

Searching the sitemap

The second function looks for the sitemap of the website and stores the list of links in a text file, one URL per line. If the file already exists, the stored list is used instead, so that the sitemap is not downloaded again each time the script runs:

def site_map(url):
    path = file_path_manager("cook_book", "site_map") / "full_list.txt"
    if not path.is_file():
        links = sitemap_search(url)
        path.write_text("\n".join(links), encoding="utf-8")
    return path

Deleting the file cook_book/site_map/full_list.txt is enough to get a fresh list. For more information on sitemaps, see this post on crawling websites with sitemaps.

Filtering the links

The third function reads the list and keeps the links containing all the given keywords. It also leaves out links containing excluded patterns:

def site_map_filter(url, keywords, excluded=()):
    links = site_map(url).read_text(encoding="utf-8").splitlines()
    return [
        link for link in links
        if all(kw in link for kw in keywords) and not any(ex in link for ex in excluded)
    ]

The list comprehension could be read as follows: “for every link in the list, keep it if all the keywords are found and none of the excluded patterns are”. On the website at hand, the recipe URLs contain the name of the dish, for example https://publicdomainrecipes.com/finnish-salmon-soup/. The keyword soup thus finds the right recipes, while the pattern /tags/ filters out the page listing all recipes tagged with “soup”.

Downloading and extracting the texts

The main() function goes through the filtered list, downloads each page, extracts its main text without comments and saves it in a numbered file. Pages which cannot be downloaded or processed are skipped. The script waits between two requests so as not to strain the website:

def main(urls, corpus_dir, output_format="txt", sleep_time=1):
    dir_path = file_path_manager("cook_book", corpus_dir)
    for i, url in enumerate(urls):
        downloaded = fetch_url(url)
        if downloaded is not None:
            result = extract(downloaded, output_format=output_format, include_comments=False)
            if result is not None:
                (dir_path / f"{i}_soup.{output_format}").write_text(result, encoding="utf-8")
        time.sleep(sleep_time)

The output_format argument is passed on to trafilatura, which can also return XML, JSON or Markdown. The file extension changes accordingly.

Running the script

Finally, the if __name__ == "__main__": block makes sure the following lines only run when the script is executed directly and not when it is imported as a module:

if __name__ == "__main__":
    url = "https://publicdomainrecipes.com/"
    soup_urls = site_map_filter(url, ["soup"], excluded=["/tags/"])
    print(len(soup_urls))
    main(soup_urls, "soup_recipes")

The script can now be executed:

$ python3 corpus_manager.py
23

Out of about 600 links in the sitemap, 23 soup recipes are found. The whole process takes less than a minute. The texts land in cook_book/soup_recipes/, from 0_soup.txt to 22_soup.txt. Here is an excerpt of the first one:

Ingredients
- 1 seasoned meat package (beef, peppers, some rub)
- 2 cans french cut green beans (or diced green beans)
- 3 small cans chicken noodle soup
...

In all, the corpus amounts to about 5,000 words.

Going further

Most of the code is about managing directories and files, while trafilatura does the heavy lifting in the background. In order to use the script in production, a few ideas to start from:

  • Add the date or the recipe name to the file names
  • Log the URLs which could not be processed
  • Download the pages in parallel, for example using the download functions of trafilatura
  • Use the same structure to build other corpora, for example by changing the keywords

Finally, please note that it is not considered fair to download a large number of pages from a website in a short period of time.