CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-duckduckgo-search

Search for words, documents, images, news, maps and text translation using the DuckDuckGo.com search engine.

Pending
Overview
Eval results
Files

news-search.mddocs/

News Search

Searches for news articles using DuckDuckGo's news search with time-based filtering and regional settings, returning structured news data with publication dates and source information.

Capabilities

News Search Function

Searches for news articles using specified keywords with filtering and configuration options.

def news(
    keywords: str,
    region: str = "us-en",
    safesearch: str = "moderate",
    timelimit: str | None = None,
    max_results: int | None = None,
) -> list[dict[str, str]]:
    """
    DuckDuckGo news search. Query params: https://duckduckgo.com/params.

    Parameters:
    - keywords (str): Search keywords/query terms  
    - region (str): Region code (us-en, uk-en, ru-ru, etc.). Defaults to "us-en".
    - safesearch (str): Safety filter level ("on", "moderate", "off"). Defaults to "moderate".
    - timelimit (str, optional): Time filter ("d", "w", "m" for day, week, month). Defaults to None.
    - max_results (int, optional): Maximum number of results to return. If None, returns results from first response only. Defaults to None.

    Returns:
    List of dictionaries with news search results containing:
    - "date" (str): Publication date in ISO format (YYYY-MM-DDTHH:MM:SS)
    - "title" (str): Article headline/title
    - "body" (str): Article excerpt/summary
    - "url" (str): Article URL
    - "image" (str): Article image URL (may be None)
    - "source" (str): News source/publication name

    Raises:
    - DuckDuckGoSearchException: Base exception for search errors
    - RatelimitException: API request rate limit exceeded
    - TimeoutException: Request timeout occurred
    """

Usage Examples

Basic news search:

from duckduckgo_search import DDGS

with DDGS() as ddgs:
    news = ddgs.news("artificial intelligence")
    for article in news:
        print(f"Title: {article['title']}")
        print(f"Date: {article['date']}")
        print(f"Source: {article['source']}")
        print(f"Summary: {article['body']}")
        print(f"URL: {article['url']}")
        if article['image']:
            print(f"Image: {article['image']}")
        print("---")

News search with time filter:

from duckduckgo_search import DDGS

with DDGS() as ddgs:
    # Search for recent news from the past day
    news = ddgs.news(
        keywords="climate change",
        region="us-en",
        safesearch="moderate",
        timelimit="d",  # Past day
        max_results=15
    )
    
    print(f"Found {len(news)} recent articles about climate change")
    
    for article in news:
        print(f"\nTitle: {article['title']}")
        print(f"Published: {article['date']}")
        print(f"Source: {article['source']}")
        print(f"Summary: {article['body'][:200]}...")  # Truncate long summaries
        print(f"Read more: {article['url']}")

Regional news search:

from duckduckgo_search import DDGS

with DDGS() as ddgs:
    # Search for technology news in different regions
    regions = [
        ("us-en", "United States"),
        ("uk-en", "United Kingdom"), 
        ("au-en", "Australia"),
        ("de-de", "Germany")
    ]
    
    for region_code, region_name in regions:
        print(f"\n=== Technology News from {region_name} ===")
        
        news = ddgs.news(
            keywords="technology innovation",
            region=region_code,
            timelimit="w",  # Past week
            max_results=5
        )
        
        for article in news:
            print(f"• {article['title']} ({article['source']})")
            print(f"  {article['date']} - {article['url']}")

News search with filtering and processing:

from duckduckgo_search import DDGS
from datetime import datetime, timezone
from collections import defaultdict

with DDGS() as ddgs:
    news = ddgs.news("space exploration", max_results=30)
    
    # Group articles by source
    by_source = defaultdict(list)
    for article in news:
        by_source[article['source']].append(article)
    
    print("Articles by source:")
    for source, articles in by_source.items():
        print(f"\n{source} ({len(articles)} articles):")
        for article in articles:
            print(f"  • {article['title']}")
            print(f"    {article['date']}")
    
    # Find most recent articles
    print("\n=== Most Recent Articles ===")
    sorted_news = sorted(news, key=lambda x: x['date'], reverse=True)
    
    for article in sorted_news[:5]:
        print(f"\n{article['title']}")
        print(f"Published: {article['date']}")
        print(f"Source: {article['source']}")
        print(f"Summary: {article['body']}")

News search with image filtering:

from duckduckgo_search import DDGS

with DDGS() as ddgs:
    news = ddgs.news("sports championship", max_results=20)
    
    # Filter articles that have images
    articles_with_images = [article for article in news if article['image']]
    
    print(f"Found {len(articles_with_images)} articles with images out of {len(news)} total")
    
    for article in articles_with_images:
        print(f"\nTitle: {article['title']}")
        print(f"Source: {article['source']}")
        print(f"Date: {article['date']}")
        print(f"Image: {article['image']}")
        print(f"Article: {article['url']}")

Error Handling

Handle news search errors:

from duckduckgo_search import DDGS
from duckduckgo_search.exceptions import (
    DuckDuckGoSearchException,
    RatelimitException,
    TimeoutException
)

try:
    with DDGS() as ddgs:
        news = ddgs.news("breaking news", max_results=50)
        print(f"Retrieved {len(news)} news articles")
        
        # Validate news data
        for article in news:
            required_fields = ['date', 'title', 'body', 'url', 'source']
            missing_fields = [field for field in required_fields if not article.get(field)]
            
            if missing_fields:
                print(f"Article missing fields {missing_fields}: {article.get('title', 'No title')}")
            else:
                print(f"Valid article: {article['title']} from {article['source']}")
                
except RatelimitException as e:
    print(f"Rate limit exceeded: {e}")
    # Implement retry with exponential backoff
    
except TimeoutException as e:
    print(f"Request timed out: {e}")
    # Retry with increased timeout
    
except DuckDuckGoSearchException as e:
    print(f"News search error: {e}")

Advanced Usage

Date parsing and analysis:

from duckduckgo_search import DDGS
from datetime import datetime, timezone
import json

with DDGS() as ddgs:
    news = ddgs.news("economy", max_results=25)
    
    # Parse and analyze publication dates
    parsed_dates = []
    for article in news:
        try:
            # Parse ISO format date
            date_obj = datetime.fromisoformat(article['date'].replace('Z', '+00:00'))
            parsed_dates.append({
                'title': article['title'],
                'source': article['source'], 
                'date': date_obj,
                'url': article['url']
            })
        except ValueError as e:
            print(f"Could not parse date '{article['date']}': {e}")
    
    # Sort by date and find date range
    if parsed_dates:
        sorted_articles = sorted(parsed_dates, key=lambda x: x['date'])
        oldest = sorted_articles[0]['date']
        newest = sorted_articles[-1]['date']
        
        print(f"Articles span from {oldest} to {newest}")
        print(f"Most recent: {sorted_articles[-1]['title']} ({sorted_articles[-1]['source']})")
        print(f"Oldest: {sorted_articles[0]['title']} ({sorted_articles[0]['source']})")

Export news data:

from duckduckgo_search import DDGS
import json
import csv

with DDGS() as ddgs:
    news = ddgs.news("renewable energy", max_results=20)
    
    # Export to JSON
    with open('news_results.json', 'w', encoding='utf-8') as f:
        json.dump(news, f, indent=2, ensure_ascii=False)
    
    # Export to CSV
    with open('news_results.csv', 'w', newline='', encoding='utf-8') as f:
        fieldnames = ['date', 'title', 'body', 'url', 'image', 'source']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(news)
    
    print(f"Exported {len(news)} articles to JSON and CSV")

Parameter Details

Time Limits

  • "d": Past day - Most recent news from the last 24 hours
  • "w": Past week - News from the last 7 days
  • "m": Past month - News from the last 30 days

SafeSearch Options

  • "on": Strict filtering, blocks potentially sensitive content
  • "moderate": Moderate filtering (default)
  • "off": No filtering

Region Codes

Common region codes for localized news results:

  • "us-en": United States (English)
  • "uk-en": United Kingdom (English)
  • "au-en": Australia (English)
  • "ca-en": Canada (English)
  • "de-de": Germany (German)
  • "fr-fr": France (French)
  • "ru-ru": Russia (Russian)
  • "jp-jp": Japan (Japanese)
  • "cn-zh": China (Chinese)
  • "in-en": India (English)

Data Format

Date Format

News article dates are returned in ISO 8601 format:

  • Format: YYYY-MM-DDTHH:MM:SS (UTC timezone)
  • Example: "2023-12-07T14:30:45"

Article Fields

Each news result contains:

  • date: ISO formatted publication timestamp
  • title: Article headline (string)
  • body: Article excerpt/summary (string, may be lengthy)
  • url: Full article URL (string)
  • image: Article image URL (string or None)
  • source: Publication/website name (string)

Image Availability

Not all news articles include images. Check if article['image'] is not None before using image URLs.

Install with Tessl CLI

npx tessl i tessl/pypi-duckduckgo-search

docs

cli.md

image-search.md

index.md

news-search.md

text-search.md

video-search.md

tile.json