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

image-search.mddocs/

Image Search

Searches for images using DuckDuckGo's image search with comprehensive filtering options including size, color, type, layout, and licensing filters, returning detailed metadata for each result.

Capabilities

Image Search Function

Searches for images using specified keywords with extensive filtering and configuration options.

def images(
    keywords: str,
    region: str = "us-en",
    safesearch: str = "moderate",
    timelimit: str | None = None,
    size: str | None = None,
    color: str | None = None,
    type_image: str | None = None,
    layout: str | None = None,
    license_image: str | None = None,
    max_results: int | None = None,
) -> list[dict[str, str]]:
    """
    DuckDuckGo images 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 ("Day", "Week", "Month", "Year"). Defaults to None.
    - size (str, optional): Image size filter ("Small", "Medium", "Large", "Wallpaper"). Defaults to None.
    - color (str, optional): Color filter ("color", "Monochrome", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Pink", "Brown", "Black", "Gray", "Teal", "White"). Defaults to None.
    - type_image (str, optional): Image type filter ("photo", "clipart", "gif", "transparent", "line"). Defaults to None.
    - layout (str, optional): Layout filter ("Square", "Tall", "Wide"). Defaults to None.
    - license_image (str, optional): License filter ("any", "Public", "Share", "ShareCommercially", "Modify", "ModifyCommercially"). 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 image search results containing:
    - "title" (str): Image title/description
    - "image" (str): Direct image URL
    - "thumbnail" (str): Thumbnail image URL
    - "url" (str): Source webpage URL
    - "height" (int): Image height in pixels
    - "width" (int): Image width in pixels  
    - "source" (str): Source domain/website name

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

Usage Examples

Basic image search:

from duckduckgo_search import DDGS

with DDGS() as ddgs:
    images = ddgs.images("cats")
    for image in images:
        print(f"Title: {image['title']}")
        print(f"Image URL: {image['image']}")
        print(f"Source: {image['url']}")
        print(f"Size: {image['width']}x{image['height']}")
        print("---")

Image search with filters:

from duckduckgo_search import DDGS

with DDGS() as ddgs:
    # Search for large, recent photos with specific color
    images = ddgs.images(
        keywords="mountain landscape",
        region="us-en",
        safesearch="moderate",
        timelimit="Month",  # Past month
        size="Large",
        color="Green", 
        type_image="photo",
        layout="Wide",
        max_results=20
    )
    
    for image in images:
        print(f"Title: {image['title']}")
        print(f"Dimensions: {image['width']}x{image['height']}")
        print(f"Source: {image['source']}")
        print(f"Image: {image['image']}")
        print("---")

Image search with Creative Commons licensing:

from duckduckgo_search import DDGS

with DDGS() as ddgs:
    # Search for images with commercial usage rights
    images = ddgs.images(
        keywords="business meeting",
        license_image="ModifyCommercially",  # Free to modify, share, and use commercially
        type_image="photo",
        size="Large",
        max_results=15
    )
    
    for image in images:
        print(f"Title: {image['title']}")
        print(f"License: Free to modify, share, and use commercially")
        print(f"Image URL: {image['image']}")
        print(f"Source: {image['url']}")
        print("---")

Download images with metadata:

from duckduckgo_search import DDGS
import requests
from pathlib import Path

def download_image(image_data, folder="images"):
    """Download image with metadata"""
    Path(folder).mkdir(exist_ok=True)
    
    try:
        response = requests.get(image_data['image'], timeout=10)
        if response.status_code == 200:
            # Create filename from title and dimensions
            safe_title = "".join(c for c in image_data['title'][:50] if c.isalnum() or c in (' ', '_')).rstrip()
            filename = f"{safe_title}_{image_data['width']}x{image_data['height']}.jpg"
            filepath = Path(folder) / filename
            
            with open(filepath, 'wb') as f:
                f.write(response.content)
            
            print(f"Downloaded: {filename}")
            return str(filepath)
    except Exception as e:
        print(f"Failed to download {image_data['title']}: {e}")
    
    return None

with DDGS() as ddgs:
    images = ddgs.images("nature photography", max_results=5)
    
    for image in images:
        print(f"Processing: {image['title']}")
        downloaded_path = download_image(image)
        if downloaded_path:
            print(f"Saved to: {downloaded_path}")

Error Handling

Handle image search errors:

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

try:
    with DDGS() as ddgs:
        images = ddgs.images("test query", max_results=100)
        print(f"Retrieved {len(images)} images")
        
        for image in images:
            # Validate image data
            required_fields = ['title', 'image', 'thumbnail', 'url', 'height', 'width', 'source']
            if all(field in image for field in required_fields):
                print(f"Valid image: {image['title']} ({image['width']}x{image['height']})")
            else:
                print(f"Incomplete image data: {image}")
                
except RatelimitException as e:
    print(f"Rate limit exceeded: {e}")
    
except TimeoutException as e:
    print(f"Request timed out: {e}")
    
except DuckDuckGoSearchException as e:
    print(f"Image search error: {e}")

Parameter Details

Size Options

  • "Small": Small images
  • "Medium": Medium-sized images
  • "Large": Large images
  • "Wallpaper": Wallpaper-sized images (typically high resolution)

Color Options

  • "color": All colors
  • "Monochrome": Black and white images
  • "Red", "Orange", "Yellow": Specific color filters
  • "Green", "Blue", "Purple": Specific color filters
  • "Pink", "Brown", "Black": Specific color filters
  • "Gray", "Teal", "White": Specific color filters

Type Options

  • "photo": Photographic images
  • "clipart": Clip art and illustrations
  • "gif": Animated GIF images
  • "transparent": Images with transparent backgrounds
  • "line": Line drawings and sketches

Layout Options

  • "Square": Square aspect ratio images
  • "Tall": Portrait orientation (taller than wide)
  • "Wide": Landscape orientation (wider than tall)

License Options

  • "any": All Creative Commons licenses
  • "Public": Public Domain (no restrictions)
  • "Share": Free to Share and Use
  • "ShareCommercially": Free to Share and Use Commercially
  • "Modify": Free to Modify, Share, and Use
  • "ModifyCommercially": Free to Modify, Share, and Use Commercially

Time Limits

  • "Day": Past day
  • "Week": Past week
  • "Month": Past month
  • "Year": Past year

SafeSearch Options

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

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