GNews Python Library

repository·master·Indexed 21 days ago

https://github.com/ranahaani/gnews

A lightweight Python package to search Google News RSS feeds and return structured JSON responses. It supports fetching news by keyword, topic, location, or site across 141 countries and 41 languages. Features include full article text extraction, real URL resolution via Playwright, async methods for concurrent fetching, and an optional SearchApi backend for enriched metadata and pagination.

Tokens
14.7K
Snippets
87
Records
96
Agent score
73%

What's inside GNews

  1. About GNews

    master
    GNews is a lightweight Python package designed to search Google News RSS feeds. It returns usable JSON responses and includes the capability to fetch full articles, eliminating the need for manual web scrapers for article content. It supports coverage across over 141 countries and 41 languages.
  2. Understand the limitations of the RSS backend

    master

    The RSS backend has several constraints compared to other potential backends:

    • Result Limit: A maximum of approximately 100 results per query.
    • Date Format: Does not provide absolute ISO dates; instead, it uses relative strings (e.g., "2 hours ago").
    • Media: No thumbnails or favicons are provided.
    • Stability: Behavior can occasionally be affected by changes to Google's RSS feeds.
  3. Limitations of full-text extraction

    master

    Full-text extraction is subject to the following constraints:

    • Paywalls: Articles behind paywalls cannot be extracted.
    • JS-heavy sites: Modern websites that rely heavily on JavaScript may block plain HTTP requests used by the extractor.
    • Bot detection: Sites protected by services like Cloudflare may block extraction attempts.

    If get_full_article() fails consistently for a specific domain, the site may be actively blocking automated requests.

  4. Understand the GNews backoff formula

    master

    GNews uses an exponential backoff formula with uniform jitter to prevent 'thundering herd' problems. The delay for each retry attempt is calculated as:

    delay = min(retry_backoff_max, retry_backoff_base * 2 ** attempt) + uniform(0, retry_backoff_base)

    Where attempt is the zero-indexed retry number.

  5. SearchApi backend limitations and behavior

    master

    When using GNews with a searchapi_key:

    • Method Compatibility: The SearchApi backend is used by get_news, get_news_by_topic, get_news_by_location, and get_news_by_site.
    • RSS Fallback: The get_top_news() method always uses the RSS backend, as SearchApi requires a specific search query to function.
    • Key Benefits: Compared to RSS, SearchApi provides absolute ISO dates, thumbnails, favicons, result ranking, pagination, and higher rate limits.
  6. Configure automatic retries and backoff in GNews

    master

    GNews automatically handles HTTP 429 (Too Many Requests) errors from Google News RSS using exponential backoff with jitter. By default, GNews performs up to 4 total attempts (1 initial request + 3 retries).

    To tune the retry behavior, you can pass the following parameters to the GNews constructor:

    • max_retries: The number of retry attempts after the initial failure.
    • retry_backoff_base: The base delay in seconds used for exponential growth.
    • retry_backoff_max: The maximum delay allowed for any single wait period.

    If you wish to disable automatic retries and revert to the behavior of version 0.8.1 (where the first 429 immediately raises a RateLimitError), set max_retries=0.

    from gnews import GNews
    
    # Custom retry configuration
    g = GNews(
        max_retries=5,           # retry up to 5 times after the initial attempt
        retry_backoff_base=2.0,  # 2s, 4s, 8s, 16s, 32s growth
        retry_backoff_max=30.0,  # cap any single wait at 30s
    )
    
    # To disable retries (reverts to 0.8.1 behavior)
    g_no_retry = GNews(max_retries=0)
  7. Set up GNews for local development

    master

    If you are contributing to the project, you can set up a development environment using Docker or a manual Git clone.

    Option 1: Setup with Docker

    1. Install docker and docker-compose.
    2. Configure the .env file with your MongoDB credentials.
    3. Run:
    docker-compose up --build

    Option 2: Install Using Git Clone

    1. Clone the repository:
    git clone https://github.com/ranahaani/GNews.git
    1. Set up a virtual environment:
    # MacOS/Linux
    virtualenv venv
    source venv/bin/activate
    
    # Windows
    virtualenv venv
    .\venv\Scripts\activate
    1. Install dependencies:
    pip install -r requirements.txt
  8. Configure the SearchApi backend

    master

    You can replace the default RSS backend with SearchApi to access more reliable Google News data. To use it, obtain an API key from SearchApi and pass it to the GNews constructor using the searchapi_key parameter. When a key is provided, methods like get_news, get_news_by_topic, get_news_by_location, and get_news_by_site will automatically use the SearchApi backend instead of RSS.

    from gnews import GNews
    
    g = GNews(searchapi_key="YOUR_SEARCHAPI_KEY", max_results=10)
    articles = g.get_news("artificial intelligence")
  9. Resolve real article URLs using Playwright

    master

    By default, the Google News RSS feed returns redirect URLs (news.google.com/rss/articles/...). To automatically resolve these into real article URLs, install the playwright extra and the Chromium browser.

    Setup:

    pip install gnews[playwright]
    playwright install chromium

    Once installed, URL resolution is automatic. If resolution fails (e.g., due to a paywall or timeout), GNews silently falls back to the Google URL without crashing. For production environments where you want to avoid Playwright, using the SearchApi backend is recommended as it returns real URLs natively.

    from gnews import GNews
    
    g = GNews(max_results=5)
    articles = g.get_news("AI")
    
    # With gnews[playwright] installed, this returns the real URL:
    print(articles[0]['url'])  # https://www.politico.com/news/...