unfluff

repository·master·Indexed 24 days ago

https://github.com/ageitgey/node-unfluff

An automatic web page content extractor for Node.js (version 3.2.0) that converts complex HTML pages into clean, plain text and structured JSON data. It provides a command-line interface and a programmatic API featuring a standard extractor and a lazy extractor for improved performance. The library extracts metadata such as title, author, date, and description, and uses a scoring algorithm to identify and extract the main article text, links, and videos.

Tokens
2.6K
Snippets
4
Records
15
Agent score
80%

What's inside unfluff

  1. Install unfluff

    master

    You can install unfluff either as a global command-line utility or as a Node.js module for programmatic use.

    To install the CLI utility globally:

    npm install -g unfluff

    To install the module for use in your Node.js project:

    npm install --save unfluff
  2. Use the extractor() function

    master

    The extractor(html, language) function is the primary way to parse HTML content programmatically. It returns a JSON object containing all extracted elements.

    Parameters:

    • html (String): The HTML content you want to parse.
    • language (String, optional): A two-letter language code. If not provided, the library attempts to auto-detect the language. Note that the extraction algorithm depends heavily on the language setting.

    Example:

    const extractor = require('unfluff');
    const data = extractor(my_html_data, 'en');
    console.log(data.text);
  3. Use the extractor.lazy() function for performance

    master

    If you are processing large documents and only need a few specific elements (like title or image), use extractor.lazy(html, language). This avoids the overhead of the full text extraction pipeline.

    Unlike the standard extractor, which returns a JSON object, extractor.lazy returns an object where every field is a function. Evaluation is only performed when the function is called, and results are cached for subsequent calls.

    Example:

    const extractor = require('unfluff');
    const data = extractor.lazy(my_html_data, 'en');
    
    // Access elements by calling them as functions
    console.log(data.title());
    console.log(data.image());
    console.log(data.text());
  4. Reference: Extracted data elements

    master

    The following fields are extracted from the provided HTML and returned in the resulting JSON object (or via function calls in the lazy version):

    • title: The document's title (from the <title> tag).
    • softTitle: A version of title with less truncation.
    • date: The document's publication date.
    • copyright: The document's copyright line, if present.
    • author: The document's author.
    • publisher: The document's publisher (website name).
    • text: The main text of the document with all the junk thrown away.
    • image: The main image for the document.
    • videos: An array of videos embedded in the article (each with src, width, and height).
    • tags: Any tags or keywords found via <rel> tags or href URLs.
    • canonicalLink: The canonical URL of the document.
    • lang: The language of the document (detected or supplied).
    • description: The description from <meta> tags.
    • favicon: The URL of the document's favicon.
    • links: An array of links embedded within the article text (each with text and href).
  5. Use the unfluff CLI

    master

    The unfluff command-line interface allows you to parse web pages by passing a filename or piping HTML content into it. The output is a JSON object containing the extracted data.

    Pass a file:

    unfluff my_file.html

    Pipe content (e.g., via curl):

    curl -s "http://somesite.com/page" | unfluff

    Example: Extract only the body text using jq:

    curl -s "https://www.polygon.com/2014/6/26/5842180/shovel-knight-review-pc-3ds-wii-u" | unfluff | jq -r .text
  6. Extract main article text and links

    master

    To extract the core content of an article, use the text and links methods. These methods rely on a topNode (the container element identified as the main content) to avoid extracting noise from sidebars or footers.

    • text(doc, topNode, lang): Returns the cleaned, formatted text of the main article. It uses a scoring algorithm to find the best content node and performs post-extraction cleanup.
    • links(doc, topNode, lang): Returns an array of objects containing { text, href } for all links found within the topNode.
    • videos(doc, topNode): Scans the topNode for video elements (iframe, embed, object, video) and returns an array of video objects containing src, height, and width.
  7. Extract page data with unfluff()

    master

    The main unfluff(html, language) function performs a full extraction of metadata and content from a provided HTML string. It parses the HTML, cleans it, identifies the best content node, and returns a single object containing all extracted elements.

    Parameters:

    • html (String): The raw HTML content to parse.
    • language (String, optional): The language of the document. If not provided, the library will attempt to detect it automatically.

    Returns: An object containing the following keys:

    • title: The page title.
    • softTitle: An alternative or secondary title.
    • date: The publication date.
    • author: The author of the content.
    • publisher: The publisher of the content.
    • copyright: Copyright information.
    • favicon: The URL to the favicon.
    • description: The page description.
    • keywords: Metadata keywords.
    • lang: The detected or provided language.
    • canonicalLink: The canonical URL.
    • tags: Associated tags.
    • image: The main image URL.
    • videos: An array of extracted video information.
    • links: An array of extracted links.
    • text: The main body text of the document.
  8. Extract metadata using the Unfluff module

    master

    The unfluff module provides a set of functions to extract structured metadata from a document (typically a Cheerio or jQuery-like object). Each function targets specific web metadata standards (like OpenGraph or Dublin Core) or common HTML patterns.

    Available extraction methods:

    • date(doc): Extracts the publication or modification date.
    • copyright(doc): Extracts copyright information.
    • author(doc): Returns an array of author names.
    • publisher(doc): Extracts the site/publisher name.
    • title(doc): Extracts the main page title, cleaning common delimiters like |, -, », or :.
    • softTitle(doc): Extracts a less aggressive version of the title.
    • image(doc): Extracts the primary image URL (e.g., from og:image).
    • favicon(doc): Extracts the favicon URL.
    • lang(doc): Extracts the document language code.
    • description(doc): Extracts the meta description.
    • keywords(doc): Extracts meta keywords.
    • canonicalLink(doc): Extracts the canonical URL.
    • tags(doc): Extracts article tags from rel='tag' links or common URL patterns (e.g., /tag/).
  9. Identify the main content node with `calculateBestNode`

    master

    The calculateBestNode(doc, lang) function implements a scoring algorithm to identify the most likely container for the main article text.

    It works by:

    1. Scanning p, pre, and td elements.
    2. Calculating a 'gravity score' based on stopword density (using the provided lang) and link density.
    3. Boosting nodes that appear to be part of a continuous text flow.
    4. Penalizing nodes with high link density or those located at the very bottom of the document.
    5. Returning the DOM node with the highest accumulated score.

    This node should be passed as the topNode to text(), links(), and videos() to ensure high-quality extraction.

  10. Use the formatter function to structure extracted data

    master

    The formatter function is the primary entrypoint for cleaning and structuring HTML content extracted from a document. It processes a DOM tree to remove noise (like low-gravity elements or short paragraphs), converts specific HTML tags (like <a>, <b>, <ul>) into plain text, and returns a cleaned string of text separated by double newlines.

    Parameters:

    • doc: The Cheerio/DOM wrapper object.
    • topNode: The root node of the content to be formatted.
    • language: (Optional) The language identifier used to filter out short paragraphs based on stopwords.

    Processing Steps:

    1. Removes nodes with a gravityScore less than 1.
    2. Converts links (<a>) to their inner HTML text.
    3. Converts line breaks (<br>) to double newlines.
    4. Flattens formatting tags (<b>, <strong>, <i>, <sup>) into plain text.
    5. Removes paragraphs that contain fewer than 3 stopwords (based on the provided language).
    6. Formats unordered lists (<ul>) into bulleted text lines.
    7. Joins all resulting text segments with double newlines (\n\n).
  11. Perform lazy extraction with unfluff.lazy()

    master

    If you only need specific parts of a document (e.g., just the title or just the text), use unfluff.lazy(html, language). This returns an object of getter functions. Each function, when called, extracts and caches its specific value. This avoids the overhead of cleaning the document and calculating the best content node unless those specific properties are requested.

    Parameters:

    • html (String): The raw HTML content.
    • language (String, optional): The language of the document.

    Returned Object Methods:

    Metadata Getters (Parsed from raw HTML):

    • title()
    • softTitle()
    • date()
    • copyright()
    • author()
    • publisher()
    • favicon()
    • description()
    • keywords()
    • lang()
    • canonicalLink()
    • tags()
    • image()

    Content Getters (Require document cleaning and node calculation):

    • videos()
    • text()
    • links()
  12. Reference the unfluff CLI options

    master

    The following options are available when using the unfluff command line interface:

    OptionAliasDescription
    --version-vShow version information
    --help-hShow this help message
    --lang(none)Override language auto-detection. Valid values are language codes like en, es, fr, etc.