### Print Hello, World! in C Source: https://github.com/caentzminger/grokipedia-py/blob/main/tests/fixtures/hello_world_program.html A classic C implementation of the 'Hello, World!' program. It utilizes the printf function from the standard input/output library to print the greeting to the console. This serves as a fundamental example for beginners in C programming. ```c int main(void) { printf("Hello, World!\n"); return 0; } ``` -------------------------------- ### Install grokipedia-py using pip Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Installs the grokipedia-py library using pip. This is the standard method for installing Python packages. ```bash pip install grokipedia-py ``` -------------------------------- ### Install grokipedia-py using uv Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Installs the grokipedia-py library using uv, a fast Python package installer and resolver. It also shows how to add the package from a Git repository. ```bash uv pip install https://github.com/caentzminger/grokipedia-py.git uv add "grokipedia-py @ git+https://github.com/caentzminger/grokipedia-py.git" ``` -------------------------------- ### Quickstart: Fetch and parse a Grokipedia page by URL Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Demonstrates how to fetch a Grokipedia page using its URL and access various attributes like title, slug, intro text, infobox, lead figure, sections, references, links, metadata, and markdown. It also shows how to convert the page data to JSON. ```python from grokipedia import from_url page = from_url("https://grokipedia.com/page/13065923") print(page.title) print(page.slug) print(page.intro_text) print(page.infobox[:3]) print(page.lead_figure) print([section.title for section in page.sections]) first_media = next( ( subsection.media for section in page.sections for subsection in section.subsections if subsection.media ), [], ) print(first_media[:1]) print(len(page.references)) print(page.links[:5]) print(page.metadata.keywords) print(page.markdown[:500]) print(page.to_json(indent=2)) ``` -------------------------------- ### Development and CI commands Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Lists common commands used for development and continuous integration within the grokipedia-py project. These commands cover setup, formatting, linting, type checking, testing, and CI execution. ```bash just setup just fmt-py just lint-py just typecheck just test just ci ``` -------------------------------- ### Resolve a Grokipedia page from its title Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Demonstrates how to get a Page object by providing the page title as a string argument to the `page` function. ```python from grokipedia import page page_obj = page('"Hello, World!" program') ``` -------------------------------- ### Fetch and Search Pages with Grokipedia Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Demonstrates how to fetch a page by its URL, parse raw HTML content, search for pages using keywords, find page URLs via a cached sitemap, refresh the sitemap manifest, and override default instance settings like timeout and robots compliance. ```python from grokipedia import Grokipedia wiki = Grokipedia() # Fetch a page by URL page_by_url = wiki.from_url("https://grokipedia.com/page/13065923") # Parse raw HTML parsed = wiki.from_html("...", source_url="https://example.com") # Search for pages matches = wiki.search("programming language") print(matches[:5]) # Find page URL using cached sitemap manifest (lazy loading) url = wiki.find_page_url('"Hello, World!" program') if url: print(f"Found: {url}") # Force refresh of sitemap manifest manifest = wiki.refresh_manifest() for sitemap_url, page_urls in manifest.items(): print(f"{sitemap_url}: {len(page_urls)} pages") # Override instance defaults per-call page_custom = wiki.page( "Python (programming language)", timeout=30.0, respect_robots=False ) ``` -------------------------------- ### Use the class-based Grokipedia API with caching Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Illustrates the usage of the `Grokipedia` class for fetching page data, searching, and finding page URLs. It highlights features like verbose output, sitemap manifest caching, and lazy lookups. ```python from grokipedia import Grokipedia wiki = Grokipedia(verbose=True) result = wiki.page("The C Programming Language") matches = wiki.search("programming language") # Lazy sitemap lookup + cached child sitemap manifests. url = wiki.find_page_url('"Hello, World!" program') manifest = wiki.refresh_manifest() ``` -------------------------------- ### Configure logging for grokipedia-py Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Shows how to configure Python's standard logging module to capture logs from the grokipedia library. It demonstrates setting the overall logging level and specifically the level for the 'grokipedia' logger. ```python import logging logging.basicConfig(level=logging.INFO) logging.getLogger("grokipedia").setLevel(logging.DEBUG) ``` -------------------------------- ### Logging Configuration for Grokipedia Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Explains how to configure Python's standard `logging` module to capture debug output from the `grokipedia` library. This includes setting the basic configuration level and specifically targeting the `grokipedia` logger for detailed information during fetch operations, or using the `verbose=True` option. ```python import logging from grokipedia import from_url, Grokipedia # Configure logging to see library debug output logging.basicConfig( level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s" ) # Set grokipedia logger to DEBUG level logging.getLogger("grokipedia").setLevel(logging.DEBUG) # Now fetch operations will log details page = from_url("https://grokipedia.com/page/13065923") # Alternatively, use verbose=True with class-based API wiki = Grokipedia(verbose=True) # Automatically configures DEBUG logging result = wiki.page("Python") ``` -------------------------------- ### Custom Fetcher Implementation in Grokipedia Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Shows how to implement the `Fetcher` protocol for custom HTTP fetching behavior, enabling integration with libraries like `requests` for testing or alternative HTTP clients. This custom fetcher can be used with both functional and class-based APIs. ```python from grokipedia import from_url, Grokipedia, FetchResponse, Fetcher from typing import Mapping class CustomFetcher: """Custom fetcher implementing the Fetcher protocol.""" def fetch_text( self, url: str, *, timeout: float, headers: Mapping[str, str], ) -> FetchResponse: # Custom HTTP implementation (e.g., using requests, httpx, aiohttp) import requests response = requests.get(url, headers=dict(headers), timeout=timeout) return FetchResponse( url=str(response.url), status_code=response.status_code, headers=dict(response.headers), text=response.text, ) # Use custom fetcher with functions custom_fetcher = CustomFetcher() page = from_url( "https://grokipedia.com/page/13065923", fetcher=custom_fetcher ) # Use custom fetcher with class-based API wiki = Grokipedia(fetcher=custom_fetcher) result = wiki.page("Python") ``` -------------------------------- ### Class-Based Grokipedia Client with Caching (Python) Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Provides a reusable Grokipedia client instance with configurable options and sitemap manifest caching for efficient, repeated lookups. Allows consistent configuration across multiple operations. ```python from grokipedia import Grokipedia # Initialize client with default options wiki = Grokipedia( timeout=10.0, respect_robots=True, verbose=True # Enable debug logging ) # Fetch a page by title page_result = wiki.page("The C Programming Language") print(page_result.title) print(page_result.intro_text) ``` -------------------------------- ### Search for Grokipedia page URLs Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Explains how to search for pages on Grokipedia using the `search` function. It also covers how to bypass robots.txt restrictions if the initial search fails. ```python from grokipedia import search results = search("hello world") print(results[:5]) # If this returns [], try: results = search("hello world", respect_robots=False) ``` -------------------------------- ### Page Data Model and Serialization in Grokipedia Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Illustrates how to use the `Page` dataclass for structured content, including generating markdown, serializing to JSON and dictionaries, reconstructing `Page` objects from these formats, and accessing page attributes like aliases and nested media. ```python from grokipedia import from_url, Page page = from_url("https://grokipedia.com/page/13065923") # Generate markdown representation markdown_output = page.markdown print(markdown_output[:500]) # Export to JSON string json_str = page.to_json(indent=2) print(json_str) # Export to dictionary data_dict = page.to_dict() # Reconstruct Page from dictionary restored_page = Page.from_dict(data_dict) # Reconstruct Page from JSON restored_from_json = Page.from_json(json_str) # Access aliases print(page.lede_text) # Alias for intro_text print(page.lead_media) # Alias for lead_figure # Access nested section media for section in page.sections: for media in section.media: print(f"Media [{media.index}]: {media.image_url}") print(f" Caption: {media.caption}") print(f" Alt: {media.alt_text}") ``` -------------------------------- ### Parse raw HTML with grokipedia-py Source: https://github.com/caentzminger/grokipedia-py/blob/main/README.md Shows how to parse raw HTML content into a Grokipedia Page object without making a network request. The source_url is required for context. ```python from grokipedia import from_html page = from_html(html, source_url="https://grokipedia.com/page/13065923") ``` -------------------------------- ### Resolve Page Title to URL and Fetch (Python) Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Resolves a human-readable Grokipedia page title to its URL, then fetches and parses the page in a single operation. Allows custom fetch options like timeout and robots.txt compliance. ```python from grokipedia import page # Resolve a page by its title result = page('"Hello, World!" program') print(result.title) print(result.url) print(result.intro_text) # Fetch with custom options result = page( "The C Programming Language", timeout=15.0, respect_robots=True, allow_robots_override=False ) # Access all parsed content print(result.markdown[:1000]) ``` -------------------------------- ### Error Handling with Grokipedia Exceptions Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Details how to handle various exceptions raised by the Grokipedia library, which all inherit from `GrokipediaError`. This includes specific exceptions for page not found, HTTP errors, robots.txt issues, network problems, parsing failures, and general library errors, as well as handling `ValueError` for search inputs. ```python from grokipedia import ( from_url, search, GrokipediaError, FetchError, HttpStatusError, PageNotFoundError, RobotsUnavailableError, RobotsDisallowedError, ParseError, ) try: page = from_url("https://grokipedia.com/page/nonexistent") except PageNotFoundError as e: print(f"Page not found: {e.url}") print(f"Status code: {e.status_code}") # Always 404 except HttpStatusError as e: print(f"HTTP error {e.status_code} for {e.url}") except RobotsDisallowedError as e: print(f"URL blocked by robots.txt: {e.url}") except RobotsUnavailableError as e: print(f"Cannot fetch/parse robots.txt: {e.robots_url}") except FetchError as e: print(f"Network error: {e}") except ParseError as e: print(f"Failed to parse content: {e}") except GrokipediaError as e: print(f"General library error: {e}") # Handle search errors try: results = search("test query") except ValueError as e: print(f"Invalid input: {e}") # e.g., empty search term except GrokipediaError as e: print(f"Search failed: {e}") ``` -------------------------------- ### Search Grokipedia Pages by Keyword (Python) Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Searches for Grokipedia pages matching a given keyword. It prioritizes the API endpoint and falls back to HTML parsing if the API is blocked by robots.txt. Supports custom timeouts and robots.txt override. ```python from grokipedia import search # Search for pages matching a query results = search("hello world") print(results[:5]) # List of page URLs # If API is blocked by robots.txt, bypass enforcement results = search("programming language", respect_robots=False) for url in results[:10]: print(url) # Search with custom timeout results = search( "machine learning", timeout=20.0, allow_robots_override=True ) ``` -------------------------------- ### Fetch and Parse Grokipedia Page by URL (Python) Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Fetches a Grokipedia page using its URL and parses it into a structured Page object. Supports custom timeouts, robots.txt enforcement, and user agent configuration. The Page object contains title, sections, infobox data, references, and metadata. ```python from grokipedia import from_url # Fetch and parse a Grokipedia page page = from_url("https://grokipedia.com/page/13065923") # Access basic page information print(page.title) # Page title print(page.slug) # URL slug identifier print(page.intro_text) # Introductory paragraph text print(page.url) # Full URL of the page # Access structured infobox data (key-value fact pairs) for field in page.infobox[:3]: print(f"{field.label}: {field.value}") # Access lead figure/image if present if page.lead_figure: print(page.lead_figure.image_url) print(page.lead_figure.caption) # Iterate through page sections for section in page.sections: print(f"Section: {section.title} (Level {section.level})") print(section.text[:200]) # Section text content for subsection in section.subsections: print(f" Subsection: {subsection.title}") # Access references and links print(f"References: {len(page.references)}") for ref in page.references[:3]: print(f"[{ref.index}] {ref.text} - {ref.url}") print(f"Links: {page.links[:5]}") # Access page metadata print(page.metadata.canonical_url) print(page.metadata.keywords) print(page.metadata.description) # Override robots.txt enforcement (use with caution) page_override = from_url( "https://grokipedia.com/page/13065923", timeout=15.0, respect_robots=False, # Skip robots.txt check user_agent="my-bot/1.0" ) ``` -------------------------------- ### Parse Raw HTML Content (Python) Source: https://context7.com/caentzminger/grokipedia-py/llms.txt Parses Grokipedia HTML content directly into a Page object without making network requests. Useful for offline processing or when HTML is already available. Supports conversion to markdown and JSON formats, and export to a dictionary. ```python from grokipedia import from_html # Parse HTML content you already have html_content = """ Example Page

Example Article

This is the introduction text.

Section One

Section content here.

""" # Parse without network requests page = from_html(html_content, source_url="https://grokipedia.com/page/example") print(page.title) print(page.intro_text) print(page.sections) # Convert to markdown representation print(page.markdown) # Export as JSON print(page.to_json(indent=2)) # Export as dictionary data = page.to_dict() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.