newspaper4k Documentation

repository·master·Indexed 22 days ago

https://github.com/andythefactory/newspaper4k

A modern continuation of the newspaper3k project, newspaper4k is a Python library for simplified article discovery and extraction. It allows users to extract text, images, authors, and metadata from news websites via a Python API or CLI. Key features include a Builder API for scraping entire websites, Google News integration, multi-threaded article downloads using fetch_news, and automatic language detection.

Tokens
18.3K
Snippets
64
Records
80
Agent score
75%

What's inside newspaper4k

  1. The Article extraction lifecycle: download, parse, and nlp

    master

    To extract data from an Article, you must follow a specific sequence of method calls:

    1. download(): Fetches the HTML. A freshly initialized article has no content until this is called. This method can be run in a multi-threaded fashion.
    2. parse(): Extracts meaningful text, title, authors, images, etc., from the downloaded HTML. Note: Calling parse() before download() will raise an ArticleException.
    3. nlp(): Performs Natural Language Processing to populate summary and keywords. This is computationally expensive and should be used sparingly. Note: You must call both download() and parse() before calling nlp(). Currently, nlp() only works on western languages.

    Available properties after parse():

    • text: The main article text.
    • title: The article title.
    • authors: A list of authors.
    • top_image: The primary image URL.
    • images: A list of all image URLs.
    • movies: A list of video URLs (YouTube, Vimeo, etc.).
    # The standard workflow
    article = newspaper.article(url='http://example.com/article')
    article.download()
    article.parse()
    
    print(article.text)
    print(article.title)
    
    # Optional NLP step
    article.nlp()
    print(article.summary)
    print(article.keywords)
  2. How keyword extraction works

    master

    Keywords are extracted from the article body using a frequency-based approach:

    1. Tokenisation: Text is split into tokens using a language-aware tokenizer; punctuation is stripped and tokens are lower-cased.
    2. Stop-word removal: Common words are removed using language-specific lists.
    3. Frequency counting: Remaining tokens are counted.
    4. Score calculation: Each keyword receives a score: $\text{score}(w) = \frac{\text{count}(w) \times 1.5}{N} + 1$, where $N$ is the total token count before stop-word removal.
    5. Ranking: Keywords are sorted by score, and the top max_keywords (default: 35) are kept. Title keywords are also processed and merged with body keywords.
  3. How extractive summarization works

    master

    Newspaper4k uses an extractive summarization method, meaning it selects the most relevant existing sentences from the article rather than generating new text. The process follows these steps:

    1. Sentence splitting: Uses NLTK Punkt tokenizer; sentences shorter than 10 characters are discarded.
    2. Keyword extraction: Extracts the top SUMMARIZE_KEYWORD_COUNT (default: 10) keywords.
    3. Sentence scoring: Each sentence is scored based on a weighted sum of four features:
      • Title similarity (Weight 1.5): Fraction of non-stop title words in the sentence.
      • Keyword frequency (Weight 2.0): An average of the Simple Bigram Score (SBS) and Density-Based Score (DBS).
      • Sentence length (Weight 1.0): Peaks near MEAN_SENTENCE_LEN (default: 20 words).
      • Sentence position (Weight 1.0): Heuristic favoring the beginning and end of the article.
    4. Selection: The highest-scoring sentences (up to max_summary_sent, default: 5) are selected and re-ordered by their original position to maintain coherence.
  4. Handle incorrect metadata via custom parsing

    master

    If a website provides incorrect metadata (for example, fox13now.com often lists the news agency as the author instead of the actual writer in meta tags), you can resolve this by implementing a custom parsing function.

    Instead of relying on the default metadata extraction, your custom function should target the article.html structure directly to extract the correct fields (like author) from the page body.

  5. Scrape whole news sources (websites) using the Source Class

    master

    Use newspaper.build(url) to create a source object for an entire website. This parses the front page, detects category links, and identifies RSS feeds to build a list of article links.

    Key Methods:

    • category_urls(): Returns a list of detected category URLs.
    • articles: A list of article objects found on the site.
    • download_articles(): Downloads all discovered articles using a multi-threaded approach. This can be slow and may lead to IP blocking if used aggressively.

    Concurrency: Downloading is multi-threaded. You can control the number of threads using the number_threads argument in build() or via Configuration.number_threads.

    import newspaper
    
    # Build the source with a specific thread count
    cnn_paper = newspaper.build('http://cnn.com', number_threads=3)
    
    # Get category URLs
    print(cnn_paper.category_urls())
    
    # Access individual articles
    article_urls = [article.url for article in cnn_paper.articles]
    
    # To download all articles in bulk:
    articles = cnn_paper.download_articles()
  6. Automatic language detection

    master

    Newspaper4k can automatically detect the language of an article. If no specific language is provided, the library attempts to detect it seamlessly during processing.

    import newspaper
    
    article = newspaper.article('https://www.bbc.com/zhongwen/simp/chinese-news-67084358')
    print(article.title)
  7. Manage article caching with memorize_articles

    master

    By default, newspaper caches previously extracted articles and will not redownload them. This prevents duplicates and increases speed. If you run build() a second time, size() will only return the number of new articles published since the last crawl.

    To disable this behavior and redownload all articles every time, set memorize_articles=False in the build() method or set the memorize_articles property on a Configuration object.

    import newspaper
    
    # Disable caching to see all articles every time
    cbs_paper = newspaper.build('http://cbs.com', memorize_articles=False)
    cbs_paper.size()
  8. Respect robots.txt using honor_robots_txt

    master

    The honor_robots_txt setting instructs newspaper4k to fetch and obey a site's robots.txt file before making requests.

    Important Details:

    • This feature only applies to Source objects and the newspaper.build helper. Plain Article downloads are not checked against robots.txt.
    • If a URL is disallowed by robots.txt, a newspaper.exceptions.RobotsException is raised.
    • The rules are checked against the Configuration.browser_user_agent used by the scraper.
    • This feature requires the protego library.
  9. Handle multi-language extraction and detection

    master

    Newspaper4k can automatically detect languages via article meta tags. If no language is specified, it defaults to English.

    Important: Accurate language detection is critical for successful text extraction. If the wrong language is detected, the parser may fail to return any text.

    Checking Language:

    • article.meta_lang: The language detected via meta tags (if use_meta_language is enabled in config).
    • article.config.language: The language explicitly set by the user.
    from newspaper import Article
    
    article = Article('https://www.bbc.com/zhongwen/simp/chinese-news-67084358')
    article.download()
    article.parse()
    
    print(article.title)
    
    if article.config.use_meta_language:
      # If using autodetected language
      print(article.meta_lang)
    else:
      print(article.config.language)
  10. Process a single article by URL

    master

    You can extract metadata and content from a specific URL using newspaper.article(url).

    Key attributes available on the article object:

    • authors: A list of author names.
    • publish_date: The publication date.
    • text: The main body text of the article.
    • top_image: The URL of the main image.
    • movies: A list of movie URLs found in the article.
    • keywords: A list of extracted keywords (requires calling .nlp()).
    • summary: A generated summary (requires calling .nlp()).

    Note: To populate keywords and summary, you must first call the .nlp() method.

    import newspaper
    
    article = newspaper.article('https://edition.cnn.com/2023/10/29/sport/nfl-week-8-how-to-watch-spt-intl/index.html')
    
    print(article.authors)
    print(article.publish_date)
    print(article.text)
    print(article.top_image)
    print(article.movies)
    
    article.nlp()
    print(article.keywords)
    print(article.summary)
  11. Use a proxy with Article and Source

    master

    To bypass IP restrictions or geographic limits, pass a proxies dictionary (compatible with the requests library) to the Article or Source constructor. The dictionary should map protocol keys (e.g., 'http', 'https') to proxy URLs.

    from newspaper import article
    
    proxies = {
        'http': 'http://your_http_proxy:port',
        'https': 'https://your_https_proxy:port'
    }
    
    url = 'https://abcnews.go.com/Technology/wireStory/indonesias-mount-marapi-erupts-leading-evacuations-reported-casualties-106358667'
    
    # Using the shortcut function
    article_obj = article(url, proxies=proxies)
    article_obj.download()
    article_obj.parse()
    
    print("Title:", article_obj.title)
  12. Scrape JavaScript-rendered websites using Playwright

    master

    Newspaper4k's default downloader may not execute JavaScript. To scrape modern websites, use Playwright to render the page, extract the HTML content, and then pass that content to Newspaper4k using the input_html parameter.

    Required packages:

    pip install newspaper4k playwright
    playwright install

    Workflow:

    1. Use Playwright to navigate to the URL and wait for rendering.
    2. Retrieve the rendered HTML via page.content().
    3. Initialize an article with newspaper.article(url, input_html=content).
    from playwright.sync_api import sync_playwright
    import newspaper
    import time
    
    def scrape_with_playwright(url):
        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.goto(url)
            time.sleep(1)  # Allow JS to render
            content = page.content()
            browser.close()
    
        # Use input_html to parse the rendered content
        article = newspaper.article(url, input_html=content, language='en')
        return article
    
    article = scrape_with_playwright('https://example.com')
    article.nlp()
    print(article.summary)