Turning saved web pages into clean Markdown

ScrapePy’s Markdown copy of a saved page keeps the article and drops the menus, adverts and sign-up boxes around it.

An example page made of navigation, a cookie banner, a newsletter box, the article, a most-read list, share buttons and a footer, with only the article highlighted, and the clean Markdown it becomes beside it. An example page made of navigation, a cookie banner, a newsletter box, the article, a most-read list, share buttons and a footer, with only the article highlighted, and the clean Markdown it becomes beside it.

A saved web page carries far more than its article: menus, cookie banners, “Most read” lists, share buttons, newsletter boxes. Each Markdown file ScrapePy writes holds the article and nothing else. The converter, scrapepy/convert/to_markdown.py, decides what goes in and hands the HTML to markdownify.

Finding the article

Feeds, XML manifests, WordPress author, category and tag pages, and error pages get no Markdown copy at all. An error page is one whose title or main heading contains a marker such as “404”, “403” or “not found”, or whose body is short and says something like “page not found” or “access denied”. For everything else, extract_content() tries several extractors in turn and takes the first result longer than 100 characters.

I put documentation platforms first, because they lay pages out in their own ways: API reference sites, Swagger UI, and help systems built with RoboHelp or MadCap Flare each have an extractor. Next comes the standard one for blogs and most other sites. It tries a list of content selectors from the most specific to the least, .entry-content for WordPress, .post-content, .article-body, article, [role='main'], main, #content and a few more, and the first that holds more than 50 words wins:

for sel in selectors:
    content = soup.select_one(sel)
    if content and len(content.get_text(strip=True).split()) > 50:
        break
else:
    return None

The word count keeps a small element that happens to match, such as an empty main or a teaser card marked up as an article, from winning over the real content further down the list. After that comes trafilatura, which is built for pulling the main text out of a page, with images, links and tables kept. The last resort strips the obvious furniture and converts whatever is in main, article or body.

Leaving out the furniture

Junk is removed twice. As HTML, scripts, styles, navigation, headers, footers and sidebars go, and so does any element whose class or id contains one of 39 keywords, such as advert, newsletter, most-read, social-share and cookie-consent:

for tag in list(soup.find_all(True)):
    if not tag.parent:
        continue  # Already decomposed with a parent element
    classes = " ".join(tag.get("class", []))
    tag_id = tag.get("id", "")
    combined = (classes + " " + tag_id).lower()
    if any(kw in combined for kw in _JUNK_CLASS_KEYWORDS):
        tag.decompose()

The loop runs over a list taken before anything is removed, so it still reaches the children of elements it has already deleted. They have no parent by then, and the check at the top skips them.

Some junk only shows up as text: “Advertisement” on a line of its own, “3 hours ago” under the headline, share counts, “Skip to main content”. Those patterns match a whole line, so the same words inside a sentence survive. Sections headed “Most Read”, “Related Articles” or “You May Also Like” are removed with everything under them. Plenty of sites mark those labels up as a bold paragraph, so bold lines are turned into headings first:

# Promote bold lines to headings first so junk section patterns
# (which match ## headings) can catch promoted junk headings
md = self.promote_bold_headings(md)

md = self.clean_markdown(md)

A line is promoted only when it’s nothing but bold text, under 80 characters, with no full stop before its end, and a bold sentence in the middle of an article stays a sentence.

The last pass tidies what’s left. A site name is stripped from the end of the main heading: “# Title | Example.com” becomes “# Title”. A short brand name after a separator goes too, but only when the title before it is at least 20 characters long. Repeated headings and images, empty links and copyright lines go, and a page left with fewer than 50 words is dropped as a list or section page with no content of its own.

Many patterns target the markup of one particular site, and the tests are grouped by site, each with samples of that site’s junk and checks that the real text around it survives. Others nest an ad-wrapper inside an ad-container to check that the nested advert goes without an error, and check that “He said this happened 2 hours ago during the meeting.” keeps its “2 hours ago” and that “Results | Round 5” keeps its second half.

The saved HTML already links to other saved files, such as news/story.html, because it was rewritten for offline reading. convert_links() points those links at the matching Markdown files. A link ending in .html or .htm gets .md instead, a link ending in a slash becomes the folder’s name plus .md, and one with no extension gets .md added. Full URLs, anchors, mailto: and tel: links are left alone, and a link to the page itself, or to an index page in the same folder or any folder above it, becomes plain text.

Running it

pip install .
scrapling install
scrapepy https://docs.example.com/guide/ --stay-in-path

The HTML goes into ScrapedSites/ and the Markdown into MarkdownSites/. Add --no-markdown to keep only the HTML. The HTML copy, and the frontmatter at the top of each Markdown file, are in Saving websites for offline reading.

More on ScrapePy

All writing about ScrapePy

Featured projects

All projects

More writing

All writing