### Example batchexecute response body Source: https://github.com/ssujitx/google-news-url-decoder Example response body with two results, deliberately reordered, from the test suite shape. The scheme is )]}'\n\n; everything before the first \n\n and the )]}' prefix line are stripped, then the remainder is json.loads-ed. Trailer rows starting with ["di", ...] and ["e", ...] are dropped. ```text )]}' [["wrb.fr","Fbv4je","[\"garturlres\",\"https://b.example/2\"]",null,null,null,"2"], ["wrb.fr","Fbv4je","[\"garturlres\",\"https://a.example/1\"]",null,null,null,"0"], ["di",1]] ``` -------------------------------- ### Install googlenewsdecoder with pip Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Installs the googlenewsdecoder package using pip. ```sh pip install googlenewsdecoder ``` -------------------------------- ### Install googlenewsdecoder with uv Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Adds the googlenewsdecoder package to the project using the uv package manager. ```sh uv add googlenewsdecoder ``` -------------------------------- ### Define __version__ from package metadata Source: https://github.com/ssujitx/google-news-url-decoder Sets the package version string from installed distribution metadata using importlib.metadata.version. Evaluated at import time; returns a string like "0.2.2" and throws PackageNotFoundError if the distribution is not installed. ```python __version__ = version("googlenewsdecoder") ``` -------------------------------- ### Sync development dependencies with uv Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Installs the project's development dependencies using uv sync with the dev group. ```sh uv sync --group dev ``` -------------------------------- ### Print __version__ Source: https://github.com/ssujitx/google-news-url-decoder Imports the package and prints its version string. Useful for verifying the installed version. ```python import googlenewsdecoder print(googlenewsdecoder.__version__) ``` -------------------------------- ### Proxy URL formats Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Example proxy URL formats accepted by the proxy parameter: HTTP, HTTPS, and SOCKS5. ```text http://user:pass@host:port https://host:port socks5://user:pass@host:port ``` -------------------------------- ### GoogleDecoder usage example Source: https://github.com/ssujitx/google-news-url-decoder Example of creating a GoogleDecoder instance with a proxy and timeout, then closing it in a finally block. The constructor is a plain function call; class usage is shown below. ```python from googlenewsdecoder import GoogleDecoder decoder = GoogleDecoder(proxy="http://user:pass@host:port", timeout=15.0) try: # ... use decoder ... pass finally: decoder.close() ``` -------------------------------- ### Fetch decoding params with get_decoding_params Source: https://github.com/ssujitx/google-news-url-decoder Fetches signature and timestamp for one article id. Returns `{"success": True, "signature", "timestamp", "base64_str"}` on success, or `{"success": False, "message"}` on failure. The GET uses `follow_redirects=False` and manually follows up to 3 redirects, aborting on external hops. ```python from googlenewsdecoder import GoogleDecoder with GoogleDecoder() as decoder: params = decoder.get_decoding_params("CBMiXYZ") if params["success"]: print(params["signature"], params["timestamp"], params["base64_str"]) ``` -------------------------------- ### GoogleDecoderAsync usage example Source: https://github.com/ssujitx/google-news-url-decoder Example of using GoogleDecoderAsync with a proxy and timeout. The decoder is created with proxy='http://user:pass@host:port' and timeout=15.0. The decode_google_news_url method is awaited, and the decoder is closed in a finally block to ensure the HTTP client is closed. ```python from googlenewsdecoder import GoogleDecoderAsync async def main(): decoder = GoogleDecoderAsync(proxy="http://user:pass@host:port", timeout=15.0) try: result = await decoder.decode_google_news_url( "https://news.google.com/rss/articles/CBMiRSS" ) print(result) finally: await decoder.close() ``` -------------------------------- ### params_page_url usage examples Source: https://github.com/ssujitx/google-news-url-decoder Shows how to call params_page_url with and without a source_url. Default locale is en-US/US/US:en; when source_url is given, its hl/gl/ceid values override the defaults. ```python from googlenewsdecoder._parse import params_page_url params_page_url("CBMi1") # -> ".../rss/articles/CBMi1?hl=en-US&gl=US&ceid=US%3Aen" params_page_url("CBMi1", "https://news.google.com/articles/CBMi1?hl=de&gl=DE&ceid=DE%3Ade") # -> ".../rss/articles/CBMi1?hl=de&gl=DE&ceid=DE%3Ade" ``` -------------------------------- ### Usage example for decode_google_news_url Source: https://github.com/ssujitx/google-news-url-decoder Shows how to use GoogleDecoderAsync to decode a single Google News URL. The result dict contains either 'decoded_url' on success or 'message' on failure. Uses an async context manager and awaits the decode method. ```python from googlenewsdecoder import GoogleDecoderAsync async def main(): async with GoogleDecoderAsync() as decoder: result = await decoder.decode_google_news_url( "https://news.google.com/read/CBMi2AFBVV95cUxPd1ZCc1lo?hl=en-US&gl=US&ceid=US%3Aen" ) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) ``` -------------------------------- ### Fetch decoding parameters with get_decoding_params Source: https://github.com/ssujitx/google-news-url-decoder Retrieve the signature and timestamp for a single Google News article ID. The method uses the RSS article page and follows redirects while confirming same-origin hops. The example prints the signature and timestamp on success, or an error message on failure. ```python from googlenewsdecoder import GoogleDecoderAsync async def main(): async with GoogleDecoderAsync() as decoder: params = await decoder.get_decoding_params( "CBMiXYZ", source_url="https://news.google.com/read/CBMiXYZ?hl=en-US&gl=US&ceid=US%3Aen", ) if params["success"]: print(params["signature"], params["timestamp"]) else: print("Params failed:", params["message"]) ``` -------------------------------- ### Async context manager usage with GoogleDecoderAsync Source: https://github.com/ssujitx/google-news-url-decoder Use `GoogleDecoderAsync` with `async with` to automatically close the underlying HTTP client. The `__aenter__` method returns `self`, and `__aexit__` calls `await self.close()`. The example decodes a Google News URL and prints the decoded URL or an error message. ```python from googlenewsdecoder import GoogleDecoderAsync async def main(): async with GoogleDecoderAsync() as decoder: result = await decoder.decode_google_news_url( "https://news.google.com/articles/CBMiXYZ" ) print(result.get("decoded_url") or result["message"]) ``` -------------------------------- ### GoogleDecoder.__init__ Source: https://github.com/ssujitx/google-news-url-decoder Constructor for the synchronous GoogleDecoder class. Accepts optional proxy, timeout, and user-agent settings, which are passed to the underlying httpx.Client. ```APIDOC ## GoogleDecoder.__init__ ### Description Constructor for the synchronous GoogleDecoder class. Accepts optional proxy, timeout, and user-agent settings, which are passed to the underlying httpx.Client. ### Parameters - **proxy** (`str | None`) - Optional - Optional HTTP/HTTPS/SOCKS5 proxy URL passed to `httpx.Client`. - **timeout** (`float | None`) - Optional - Seconds per HTTP operation; `None` waits indefinitely. Passed through to httpx (applies to connect/read/write/pool). - **user_agent** (`str | None`) - Optional - Optional `User-Agent` header value (set as `{"User-Agent": ...}`). `None` sends httpx's default headers (no explicit UA). ``` -------------------------------- ### Define __all__ exports Source: https://github.com/ssujitx/google-news-url-decoder Lists the public names exported by `from googlenewsdecoder import *`. Includes GoogleDecoder, GoogleDecoderAsync, gnews_decoder_async, and gnewsdecoder. ```python __all__ = [ "GoogleDecoder", "GoogleDecoderAsync", "gnews_decoder_async", "gnewsdecoder", ] ``` -------------------------------- ### GoogleDecoder.__init__(proxy, timeout, user_agent) Source: https://github.com/ssujitx/google-news-url-decoder Constructor for the GoogleDecoder class. Creates an internal httpx.Client with the provided proxy, timeout, and user agent settings. Use as a context manager or call close() to release the HTTP client. ```APIDOC ## GoogleDecoder.__init__(proxy, timeout, user_agent) ### Description Constructor for the GoogleDecoder class. Creates an internal httpx.Client with the provided proxy, timeout, and user agent settings. Use as a context manager or call close() to release the HTTP client. ### Method Constructor ### Signature ```python def __init__( self, proxy: str | None = None, timeout: float | None = 10.0, user_agent: str | None = None, ): ``` ### Parameters - **proxy** (str | None) - Optional - HTTP/HTTPS/SOCKS5 proxy URL passed to httpx.Client(proxy=...). Examples: http://user:pass@host:port, socks5://host:port. - **timeout** (float | None) - Optional - Seconds per HTTP operation; None waits indefinitely. Passed through to httpx. - **user_agent** (str | None) - Optional - User-Agent header value. None uses httpx's default. ### Usage Example ```python from googlenewsdecoder import GoogleDecoder decoder = GoogleDecoder(proxy="http://user:pass@host:port", timeout=15.0) try: # ... use decoder ... pass finally: decoder.close() ``` ``` -------------------------------- ### article_id usage examples Source: https://github.com/ssujitx/google-news-url-decoder Shows how to call article_id with valid and invalid URLs. The function returns the article id for news.google.com URLs with /read/ or /rss/articles/ paths, and None for non-Google hosts. ```python from googlenewsdecoder._parse import article_id assert article_id("https://news.google.com/read/CBMiABC123?hl=en-US") == "CBMiABC123" assert article_id("https://news.google.com/rss/articles/CBMiRSS?oc=5") == "CBMiRSS" assert article_id("https://example.com/articles/CBMiABC") is None ``` -------------------------------- ### GoogleDecoderAsync.__init__ Source: https://github.com/ssujitx/google-news-url-decoder Constructor for the asynchronous GoogleDecoderAsync class. Accepts optional proxy, timeout, and user-agent settings, which are passed to the underlying httpx.AsyncClient. ```APIDOC ## GoogleDecoderAsync.__init__ ### Description Constructor for the asynchronous GoogleDecoderAsync class. Accepts optional proxy, timeout, and user-agent settings, which are passed to the underlying httpx.AsyncClient. ### Parameters - **proxy** (`str | None`) - Optional - Optional HTTP/HTTPS/SOCKS5 proxy URL passed to `httpx.AsyncClient`. - **timeout** (`float | None`) - Optional - Seconds per HTTP operation; `None` waits indefinitely. Passed through to httpx (applies to connect/read/write/pool). - **user_agent** (`str | None`) - Optional - Optional `User-Agent` header value (set as `{"User-Agent": ...}`). `None` sends httpx's default headers (no explicit UA). ``` -------------------------------- ### GoogleDecoder.__init__ signature Source: https://github.com/ssujitx/google-news-url-decoder Constructor signature for GoogleDecoder. Creates the internal httpx.Client with proxy, follow_redirects=True, timeout, http2=True, and headers with User-Agent if provided. No exceptions are declared or wrapped; a proxy value httpx rejects raises at httpx.Client construction and propagates to the caller. ```python def __init__( self, proxy: str | None = None, timeout: float | None = 10.0, user_agent: str | None = None, ): ``` -------------------------------- ### gnewsdecoder with error handling, proxy, and timeout Source: https://github.com/ssujitx/google-news-url-decoder Decodes a Google News RSS article URL with optional interval, proxy, and timeout parameters. Wraps the call in a try/except to catch exceptions that may arise from client construction or outside the decoder's error handlers. ```python from googlenewsdecoder import gnewsdecoder try: result = gnewsdecoder( "https://news.google.com/rss/articles/CBMiRSS?oc=5", interval=1, # wait after the article-page fetch proxy="http://user:pass@host:port", # optional timeout=15.0, # None waits indefinitely ) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) except Exception as exc: print(f"Error occurred: {exc}") ``` -------------------------------- ### Basic single URL call with gnews_decoder_async Source: https://github.com/ssujitx/google-news-url-decoder Decodes a single Google News URL asynchronously. Checks the success flag and prints the decoded URL or error message. Requires asyncio and the googlenewsdecoder package. ```python import asyncio from googlenewsdecoder import gnews_decoder_async async def main(): result = await gnews_decoder_async( "https://news.google.com/rss/articles/CBMiRSS?hl=en-US&gl=US&ceid=US%3Aen" ) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) asyncio.run(main()) ``` -------------------------------- ### POST batchexecute request headers Source: https://github.com/ssujitx/google-news-url-decoder HTTP request line and Content-Type header for the batchexecute RPC endpoint. Sent by _batchexecute() via response.raise_for_status(); any non-2xx raises an httpx.HTTPError. ```http POST https://news.google.com/_/DotsSplashUi/data/batchexecute Content-Type: application/x-www-form-urlencoded;charset=UTF-8 ``` -------------------------------- ### Wrap construction-time and unexpected exceptions with GoogleDecoder Source: https://github.com/ssujitx/google-news-url-decoder Catches exceptions that escape the library, such as httpx proxy parsing errors at client construction or parser errors outside declared handlers. Use try/except around the entire call. ```python from googlenewsdecoder import GoogleDecoder try: with GoogleDecoder(proxy="http://user:pass@host:port") as decoder: result = decoder.decode_google_news_url("https://news.google.com/articles/CBMiXYZ") except Exception as exc: print(f"Error occurred: {exc}") ``` -------------------------------- ### GoogleDecoderAsync.__init__(proxy, timeout, user_agent) Source: https://github.com/ssujitx/google-news-url-decoder Constructor for the asynchronous decoder class. Creates an internal httpx.AsyncClient with the provided proxy, timeout, and user agent settings. ```APIDOC ## GoogleDecoderAsync.__init__(proxy, timeout, user_agent) ### Description Constructor for the asynchronous decoder class. Creates an internal `httpx.AsyncClient` with the provided proxy, timeout, and user agent settings. ### Method Constructor ### Parameters - **proxy** (`str | None`) - Optional - Optional HTTP/HTTPS/SOCKS5 proxy URL passed to `httpx.AsyncClient(proxy=...)`. - **timeout** (`float | None`) - Optional - Seconds per HTTP operation; `None` waits indefinitely. Passed through to httpx. - **user_agent** (`str | None`) - Optional - Optional `User-Agent` header value. `None` uses httpx's default. ### Example ```python from googlenewsdecoder import GoogleDecoderAsync async def main(): decoder = GoogleDecoderAsync(proxy="http://user:pass@host:port", timeout=15.0) try: result = await decoder.decode_google_news_url( "https://news.google.com/rss/articles/CBMiRSS" ) print(result) finally: await decoder.close() ``` ``` -------------------------------- ### __enter__ Source: https://github.com/ssujitx/google-news-url-decoder Returns self so the decoder can be used with the `with` statement. ```APIDOC ## __enter__ ### Description Returns `self` so the decoder can be used with `with`. ### Method __enter__ ### Endpoint `googlenewsdecoder/decoder.py:47` ### Parameters None ### Response #### Success Response - **self** (GoogleDecoder) - The decoder instance. ### Request Example ```python def __enter__(self) -> GoogleDecoder: ``` ``` -------------------------------- ### Basic gnewsdecoder usage Source: https://github.com/ssujitx/google-news-url-decoder Decodes a single Google News URL and prints the decoded URL or an error message. The result dict contains 'success' and either 'decoded_url' or 'message'. ```python from googlenewsdecoder import gnewsdecoder source_url = ( "https://news.google.com/read/CBMi2AFBVV95cUxPd1ZCc1loODVVNHpnbFFT" "?hl=en-US&gl=US&ceid=US%3Aen" ) result = gnewsdecoder(source_url) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) ``` -------------------------------- ### Batch decode with concurrency and per-item error handling Source: https://github.com/ssujitx/google-news-url-decoder Decodes multiple Google News URLs in parallel, capped by the concurrency parameter (default 8). Uses interval to wait between article-page fetches; None means no wait. Handles per-item failures via the success flag and catches exceptions from the batch call. ```python import asyncio from googlenewsdecoder import gnews_decoder_async URLS = [ "https://news.google.com/read/CBMi...", "https://news.google.com/rss/articles/CBMi...", "https://news.google.com/articles/CBMi...", ] async def main(): try: results = await gnews_decoder_async( URLS, concurrency=4, # default 8; cap parallel article fetches interval=1, # optional; None means no wait ) for result in results: if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) except Exception as exc: print(f"Error occurred: {exc}") asyncio.run(main()) ``` -------------------------------- ### Async decoding with gnews_decoder_async Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Decodes a single Google News URL asynchronously using asyncio.run(). Accepts the same optional parameters as the sync version. Handles success and error cases in the result dictionary. ```python import asyncio from googlenewsdecoder import gnews_decoder_async def main(): interval_time = 1 # optional; None means no wait timeout = 15.0 # Optional. Examples: # proxy = "http://user:pass@host:port" # proxy = "https://host:port" # proxy = "socks5://user:pass@host:port" proxy = None source_url = "https://news.google.com/read/CBMi2AFBVV95cUxPd1ZCc1loODVVNHpnbFFTVHFkTG94eWh1NWhTeE9yT1RyNTRXMVV2S1VIUFM3ZlVkVjl6UHh3RkJ0bXdaTVRlcHBjMWFWTkhvZWVuM3pBMEtEdlllRDBveGdIUm9GUnJ4ajd1YWR5cWs3VFA5V2dsZnY1RDZhVDdORHRSSE9EalF2TndWdlh4bkJOWU5UMTdIV2RCc285Q2p3MFA4WnpodUNqN1RNREMwa3d5T2ZHS0JlX0MySGZLc01kWDNtUEkzemtkbWhTZXdQTmdfU1JJaXY?hl=en-US&gl=US&ceid=US%3Aen" try: result = asyncio.run( gnews_decoder_async( source_url, interval=interval_time, proxy=proxy, timeout=timeout, ) ) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) except Exception as e: print(f"Error occurred: {e}") if __name__ == "__main__": main() ``` -------------------------------- ### gnewsdecoder Source: https://github.com/ssujitx/google-news-url-decoder Synchronous convenience function that decodes one Google News URL, or a list of them, to the original article URL. It constructs a GoogleDecoder client, runs the decode, and closes the client in one step. ```APIDOC ## gnewsdecoder ### Description Synchronous convenience function. Decodes one Google News URL, or a list of them, to the original article URL. ### Method Function call ### Signature ```python def gnewsdecoder( source_url: str | list[str], interval: int | None = None, proxy: str | None = None, timeout: float | None = 10.0, ) -> dict | list[dict]: ``` ### Parameters - **source_url** (`str | list[str]`) - Required - One Google News URL, or a list of them (`/read/`, `/articles/`, or `/rss/articles/`). A string returns one dict; a list uses one `batchexecute` POST and returns a list of dicts. - **interval** (`int | None`) - Optional - Seconds to wait after each article-page fetch. `None` means no wait. Use on large batches if you hit HTTP 429. - **proxy** (`str | None`) - Optional - Optional HTTP/HTTPS/SOCKS5 proxy URL. Examples: `http://user:pass@host:port`, `https://host:port`, `socks5://host:port`. - **timeout** (`float | None`) - Optional - Seconds per HTTP operation. `None` waits indefinitely. ### Return type `dict | list[dict]` — one result dict when `source_url` is a string; one result dict per input URL, in input order, when it is a list. Shape per item: `{"success": True, "decoded_url": "..."}` or `{"success": False, "message": "..."}` (see [types.md](../types.md)). ### Behavior & throws Constructs `GoogleDecoder(proxy=proxy, timeout=timeout)` inside a `with` block and calls `decode_google_news_url(source_url, interval=interval)` (string) or `decode_google_news_urls(source_url, interval=interval)` (list). The `user_agent` option is **not** exposed on this convenience function — use `GoogleDecoder` directly for that. Failures are returned as result dicts, not raised. Exceptions that can still reach the caller come from constructing the `httpx.Client` (e.g., a proxy URL that httpx cannot parse) and any exception raised outside the `httpx.HTTPError`/parse-error handlers inside the decoder. ### Request Example ```python from googlenewsdecoder import gnewsdecoder source_url = ( "https://news.google.com/read/CBMi2AFBVV95cUxPd1ZCc1loODVVNHpnbFFT" "?hl=en-US&gl=US&ceid=US%3Aen" ) result = gnewsdecoder(source_url) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) ``` ### Request Example (with options) ```python from googlenewsdecoder import gnewsdecoder try: result = gnewsdecoder( "https://news.google.com/rss/articles/CBMiRSS?oc=5", interval=1, # wait after the article-page fetch proxy="http://user:pass@host:port", # optional timeout=15.0, # None waits indefinitely ) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) except Exception as exc: print(f"Error occurred: {exc}") ``` ``` -------------------------------- ### gnews_decoder_async Source: https://github.com/ssujitx/google-news-url-decoder Asynchronous convenience function that decodes Google News URLs. It is the async version of gnewsdecoder with the same return shape, supporting single URLs or batches with concurrency control. ```APIDOC ## gnews_decoder_async ### Description Asynchronous convenience function. Async version of `gnewsdecoder` with the same return shape. ### Signature ```python async def gnews_decoder_async( source_url: str | list[str], interval: int | None = None, proxy: str | None = None, timeout: float | None = 10.0, concurrency: int = 8, ) -> dict | list[dict]: ``` ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `source_url` | `str \| list[str]` | yes | — | One Google News URL, or a list of them. | | `interval` | `int \| None` | no | `None` | Seconds to wait after each article-page fetch. `None` means no wait. | | `proxy` | `str \| None` | no | `None` | Optional HTTP/HTTPS/SOCKS5 proxy URL. | | `timeout` | `float \| None` | no | `10.0` | Seconds per HTTP operation. `None` waits indefinitely. | | `concurrency` | `int` | no | `8` | Max parallel article-page fetches when `source_url` is a list. | ### Return type `dict | list[dict]` — same shape as `gnewsdecoder`. When `source_url` is a list, article pages are fetched in parallel (capped by `concurrency`) and the decode is still one POST. ### Behavior & throws Constructs `GoogleDecoderAsync(proxy=proxy, timeout=timeout)` in an `async with` block and calls `decode_google_news_url` / `decode_google_news_urls`. For a single string, the underlying `decode_google_news_url` forces `concurrency=1`. Failures are returned as result dicts (see [errors.md](../errors.md)); construction-time exceptions propagate. ### Request Example Basic call, single URL: ```python import asyncio from googlenewsdecoder import gnews_decoder_async async def main(): result = await gnews_decoder_async( "https://news.google.com/rss/articles/CBMiRSS?hl=en-US&gl=US&ceid=US%3Aen" ) if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) asyncio.run(main()) ``` Batch with concurrency and error handling per item: ```python import asyncio from googlenewsdecoder import gnews_decoder_async URLS = [ "https://news.google.com/read/CBMi...", "https://news.google.com/rss/articles/CBMi...", "https://news.google.com/articles/CBMi...", ] async def main(): try: results = await gnews_decoder_async( URLS, concurrency=4, # default 8; cap parallel article fetches interval=1, # optional; None means no wait ) for result in results: if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) except Exception as exc: print(f"Error occurred: {exc}") asyncio.run(main()) ``` ``` -------------------------------- ### _batchexecute(items) private method definition Source: https://github.com/ssujitx/google-news-url-decoder Private member that POSTs collected ids to BATCHEXECUTE_URL with Content-Type: application/x-www-form-urlencoded;charset=UTF-8 and body build_batchexecute_body(items), then parse_batchexecute() extracts result pairs. The annotation and docstring describe 3-tuples, but the sole call site passes 4-tuples (request_id, article_id, timestamp, signature). Returns dict with success flag and pairs or error message. ```python def _batchexecute(self, items: list[tuple[str, str, str]]) -> dict: """POST one or many ids to batchexecute. items are (id, timestamp, signature).""" ``` -------------------------------- ### gnews_decoder_async function signature Source: https://github.com/ssujitx/google-news-url-decoder Async version of gnewsdecoder with the same return shape. Constructs GoogleDecoderAsync in an async with block and calls decode_google_news_url or decode_google_news_urls. For a single string, the underlying decode_google_news_url forces concurrency=1. ```python async def gnews_decoder_async( source_url: str | list[str], interval: int | None = None, proxy: str | None = None, timeout: float | None = 10.0, concurrency: int = 8, ) -> dict | list[dict]: ``` -------------------------------- ### Async batch decoding with gnews_decoder_async Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Decodes multiple Google News URLs asynchronously by passing a list. Article pages can run in parallel, but the decode operation is still a single POST. Iterates over results to print each decoded URL or error. ```python import asyncio from googlenewsdecoder import gnews_decoder_async def main(): interval_time = 1 # optional; None means no wait timeout = 15.0 # Optional. Examples: # proxy = "http://user:pass@host:port" # proxy = "https://host:port" # proxy = "socks5://user:pass@host:port" proxy = None source_urls = [ "https://news.google.com/read/CBMi2AFBVV95cUxPd1ZCc1loODVVNHpnbFFTVHFkTG94eWh1NWhTeE9yT1RyNTRXMVV2S1VIUFM3ZlVkVjl6UHh3RkJ0bXdaTVRlcHBjMWFWTkhvZWVuM3pBMEtEdlllRDBveGdIUm9GUnJ4ajd1YWR5cWs3VFA5V2dsZnY1RDZhVDdORHRSSE9EalF2TndWdlh4bkJOWU5UMTdIV2RCc285Q2p3MFA4WnpodUNqN1RNREMwa3d5T2ZHS0JlX0MySGZLc01kWDNtUEkzemtkbWhTZXdQTmdfU1JJaXY?hl=en-US&gl=US&ceid=US%3Aen", "https://news.google.com/rss/articles/CBMiiAFBVV95cUxQOXZLdC1hSzFqQVVLWGJVZzlPaDYyNjdWTURScV9BbVp0SWhFNzZpSWZxSzdhc0tKbVlHMU13NmZVOFdidFFkajZPTm9SRnlZMWFRZ01CVHh0dXU0TjNVMUxZNk9Ibk5DV3hrYlRiZ20zYkIzSFhMQVVpcTFPc00xQjhhcGV1aXM?hl=en-US&gl=US&ceid=US%3Aen", ] try: results = asyncio.run( gnews_decoder_async( source_urls, interval=interval_time, proxy=proxy, timeout=timeout, ) ) for result in results: if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) except Exception as e: print(f"Error occurred: {e}") if __name__ == "__main__": main() ``` -------------------------------- ### Batch decode with proxy and concurrency=2 Source: https://github.com/ssujitx/google-news-url-decoder Shows how to decode a list of Google News URLs using a SOCKS5 proxy and a concurrency limit of 2. Prints the count of successfully decoded URLs out of the total. ```python async def main2(): async with GoogleDecoderAsync(proxy="socks5://user:pass@host:port") as decoder: results = await decoder.decode_google_news_urls( ["https://news.google.com/articles/CBMi1", "https://news.google.com/articles/CBMi2"], concurrency=2, ) successes = sum(1 for r in results if r["success"]) print(f"{successes}/{len(results)} decoded") ``` -------------------------------- ### GoogleDecoder class docstring Source: https://github.com/ssujitx/google-news-url-decoder Class docstring for the synchronous decoder. Use as a context manager so the HTTP client is closed. Parameters: proxy (optional HTTP/HTTPS/SOCKS5 proxy URL), timeout (seconds per HTTP operation, None waits indefinitely), user_agent (optional User-Agent, None uses httpx's default). ```python class GoogleDecoder: """Synchronous decoder. Use as a context manager so the HTTP client is closed. Parameters: proxy: Optional HTTP/HTTPS/SOCKS5 proxy URL. Examples: ``http://user:pass@host:port``, ``socks5://host:port``. timeout: Seconds per HTTP operation. None waits indefinitely. user_agent: Optional User-Agent. None uses httpx's default. """ ``` -------------------------------- ### _batchexecute(items) private method Source: https://github.com/ssujitx/google-news-url-decoder Private async twin of GoogleDecoder._batchexecute. Posts one or many ids to batchexecute; items are (id, timestamp, signature). Same wire format, returned shapes, and error-message mapping as the sync version. The only call site passes 4-tuples (request_id, article_id, timestamp, signature) where request_id is the input-list index as a string. ```python async def _batchexecute(self, items: list[tuple[str, str, str]]) -> dict: """POST one or many ids to batchexecute. items are (id, timestamp, signature).""" ``` -------------------------------- ### Per-result failure handling with gnewsdecoder Source: https://github.com/ssujitx/google-news-url-decoder Checks the 'success' key in each result dict; failures never raise and are reported via 'message'. Works for both single URL and list input. ```python from googlenewsdecoder import gnewsdecoder result = gnewsdecoder("https://news.google.com/rss/articles/CBMiRSS") if result["success"]: print("Decoded URL:", result["decoded_url"]) else: # result["message"] is one of the catalog strings above print("Decode failed:", result["message"]) for result in gnewsdecoder(["https://example.com/x", "https://news.google.com/articles/CBMi1"]): if not result["success"]: print("Item failed:", result["message"]) ``` -------------------------------- ### Decode with timeout=None and error handling Source: https://github.com/ssujitx/google-news-url-decoder Creates GoogleDecoder with timeout=None and decodes an /rss/articles/ URL. Prints 'Decoded URL:' on success or 'Error:' with message on failure. ```python with GoogleDecoder(timeout=None) as decoder: result = decoder.decode_google_news_url("https://news.google.com/rss/articles/CBMiRSS") if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) ``` -------------------------------- ### gnews_decoder_async (batch) Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Asynchronous batch decoding of multiple Google News URLs. Accepts a list of URLs and returns a list of dictionaries with decoded URLs or error messages. ```APIDOC ## gnews_decoder_async (batch) ### Description Asynchronous batch decoding of multiple Google News URLs. Accepts a list of URLs and returns a list of dictionaries with decoded URLs or error messages. ### Method Async function call ### Endpoint `gnews_decoder_async(source_urls, interval=None, proxy=None, timeout=15.0)` ### Parameters - **source_urls** (list) - Required - List of Google News URLs to decode. - **interval** (float, optional) - Optional - Time to wait between requests. Default is None (no wait). - **proxy** (str, optional) - Optional - Proxy URL to use. Examples: `http://user:pass@host:port`, `https://host:port`, `socks5://user:pass@host:port`. - **timeout** (float, optional) - Optional - Timeout for the request. Default is 15.0. ### Response #### Success Response - **success** (bool) - Indicates if the decoding was successful. - **decoded_url** (str) - The decoded URL. #### Error Response - **success** (bool) - Indicates if the decoding failed. - **message** (str) - Error message. ### Request Example ```python import asyncio from googlenewsdecoder import gnews_decoder_async source_urls = [ "https://news.google.com/read/CBMi2AFBVV95cUxPd1ZCc1loODVVNHpnbFFTVHFkTG94eWh1NWhTeE9yT1RyNTRXMVV2S1VIUFM3ZlVkVjl6UHh3RkJ0bXdaTVRlcHBjMWFWTkhvZWVuM3pBMEtEdlllRDBveGdIUm9GUnJ4ajd1YWR5cWs3VFA5V2dsZnY1RDZhVDdORHRSSE9EalF2TndWdlh4bkJOWU5UMTdIV2RCc285Q2p3MFA4WnpodUNqN1RNREMwa3d5T2ZHS0JlX0MySGZLc01kWDNtUEkzemtkbWhTZXdQTmdfU1JJaXY?hl=en-US&gl=US&ceid=US%3Aen", "https://news.google.com/rss/articles/CBMiiAFBVV95cUxQOXZLdC1hSzFqQVVLWGJVZzlPaDYyNjdWTURScV9BbVp0SWhFNzZpSWZxSzdhc0tKbVlHMU13NmZVOFdidFFkajZPTm9SRnlZMWFRZ01CVHh0dXU0TjNVMUxZNk9Ibk5DV3hrYlRiZ20zYkIzSFhMQVVpcTFPc00xQjhhcGV1aXM?hl=en-US&gl=US&ceid=US%3Aen" ] results = asyncio.run(gnews_decoder_async(source_urls, interval=1, proxy=None, timeout=15.0)) for result in results: if result["success"]: print("Decoded URL:", result["decoded_url"]) else: print("Error:", result["message"]) ``` ``` -------------------------------- ### GoogleDecoderAsync class docstring Source: https://github.com/ssujitx/google-news-url-decoder Class docstring for GoogleDecoderAsync, an async decoder mirroring GoogleDecoder. Use `async with` to ensure the underlying httpx.AsyncClient is closed. Parameters: proxy (optional HTTP/HTTPS/SOCKS5 proxy URL), timeout (seconds per HTTP operation, None waits indefinitely), user_agent (optional User-Agent, None uses httpx's default). ```python class GoogleDecoderAsync: """Async decoder. Use ``async with`` so the HTTP client is closed. Parameters: proxy: Optional HTTP/HTTPS/SOCKS5 proxy URL. Examples: ``http://user:pass@host:port``, ``socks5://host:port``. timeout: Seconds per HTTP operation. None waits indefinitely. user_agent: Optional User-Agent. None uses httpx's default. """ ``` -------------------------------- ### Consumer pattern for result dict Source: https://github.com/ssujitx/google-news-url-decoder Shows how to check success and extract decoded_url or message from the result dict. ```python result = gnewsdecoder(url) if result["success"]: url = result["decoded_url"] else: reason = result["message"] ``` -------------------------------- ### params_page_url(art_id, source_url) Source: https://github.com/ssujitx/google-news-url-decoder Builds the article-page URL whose HTML contains the signature. It copies locale parameters from the source URL when provided, otherwise uses defaults. ```APIDOC ## params_page_url(art_id, source_url) ### Description Article-page URL that actually returns `data-n-a-sg`. `/articles/{id}` and `/read/{id}` 302 to `google.com/sorry` from non-browser clients. `/rss/articles/{id}?hl=&gl=&ceid=` returns 200. Locale is copied from `source_url` when present. ### Parameters - **art_id** (str) - Required - Article id inserted into `RSS_ARTICLE_URL`. - **source_url** (str | None) - Optional - Source URL whose `hl`/`gl`/`ceid` query params are copied. ### Returns - **str** - The article-page URL, e.g. `https://news.google.com/rss/articles/CBMi1?hl=en-US&gl=US&ceid=US%3Aen`. ### Example ```python from googlenewsdecoder._parse import params_page_url params_page_url("CBMi1") # -> ".../rss/articles/CBMi1?hl=en-US&gl=US&ceid=US%3Aen" params_page_url("CBMi1", "https://news.google.com/articles/CBMi1?hl=de&gl=DE&ceid=DE%3Ade") # -> ".../rss/articles/CBMi1?hl=de&gl=DE&ceid=DE%3Ade" ``` ``` -------------------------------- ### Upgrade googlenewsdecoder with pip Source: https://github.com/ssujitx/google-news-url-decoder/blob/main/README.md Upgrades the googlenewsdecoder package to the latest version using pip. ```sh pip install googlenewsdecoder --upgrade ``` -------------------------------- ### Module-level constants and regex patterns Source: https://github.com/ssujitx/google-news-url-decoder Defines regex patterns for signature and timestamp attributes, endpoint URLs, and the static RPC context blob used in batchexecute payloads. ```python _SG = re.compile(r'data-n-a-sg="([^"]+)"') _TS = re.compile(r'data-n-a-ts="([^"]+)"') BATCHEXECUTE_URL = "https://news.google.com/_/DotsSplashUi/data/batchexecute" RSS_ARTICLE_URL = "https://news.google.com/rss/articles/{id}" _GARTURLREQ_CTX = [ ["X", "X", ["X", "X"], None, None, 1, 1, "US:en", None, 1, None, None, None, None, None, 0, 1], "X", "X", 1, [1, 1, 1], 1, 1, None, 0, 0, None, 0, ] ``` -------------------------------- ### gnewsdecoder function signature Source: https://github.com/ssujitx/google-news-url-decoder Synchronous convenience function that decodes one Google News URL or a list of them. Accepts optional interval, proxy, and timeout parameters. Returns a dict for a single URL or a list of dicts for a list. ```python def gnewsdecoder( source_url: str | list[str], interval: int | None = None, proxy: str | None = None, timeout: float | None = 10.0, ) -> dict | list[dict]: ``` -------------------------------- ### __aexit__ Source: https://github.com/ssujitx/google-news-url-decoder Async context manager exit point. Calls await self.close(). ```APIDOC ## __aexit__ ### Description Async context manager exit point. Calls `await self.close()`. ### Method `__aexit__` ### Signature ```python async def __aexit__(self, *exc) -> None: ``` ### Parameters - `*exc` - exception details ### Returns - `None` ``` -------------------------------- ### __exit__ Source: https://github.com/ssujitx/google-news-url-decoder Calls `self.close()` when exiting the context manager. ```APIDOC ## __exit__ ### Description Calls `self.close()`. ### Method __exit__ ### Endpoint `googlenewsdecoder/decoder.py:50` ### Parameters - **exc** (tuple) - Optional - Exception details passed by the context manager protocol. ### Response #### Success Response - **None** - No return value. ### Request Example ```python def __exit__(self, *exc) -> None: ``` ### Response Example ```python from googlenewsdecoder import GoogleDecoder with GoogleDecoder() as decoder: result = decoder.decode_google_news_url("https://news.google.com/articles/CBMiXYZ") # client is closed automatically on exit ``` ``` -------------------------------- ### __aenter__ Source: https://github.com/ssujitx/google-news-url-decoder Async context manager entry point. Returns self for use with async with. ```APIDOC ## __aenter__ ### Description Async context manager entry point. Returns self for use with `async with`. ### Method `__aenter__` ### Signature ```python async def __aenter__(self) -> GoogleDecoderAsync: ``` ### Returns - `GoogleDecoderAsync` - self ``` -------------------------------- ### decode_google_news_urls method signature Source: https://github.com/ssujitx/google-news-url-decoder Batch decode method that fetches article pages sequentially and decodes them in a single POST. Optional interval adds a sleep after each fetch. Returns one result dict per input URL in order. ```python def decode_google_news_urls( self, source_urls: list[str], interval: int | None = None ) -> list[dict]: """Decode many URLs. Article pages are fetched in order, then one POST. Parameters: source_urls: Google News URLs. interval: Seconds to wait after each article-page fetch. None means no wait. Returns: One result dict per input URL, in the same order. """ ``` -------------------------------- ### Result dict success shape Source: https://github.com/ssujitx/google-news-url-decoder Returned by ok() builder on successful decode. Contains success flag and decoded_url. ```python {"success": True, "decoded_url": str} ```