### Proxy Configuration with Noble TLS Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Demonstrates proxy configuration using noble-tls library. Shows two methods: per-request proxy configuration and session-wide proxy setup. Includes authentication with username/password in proxy URLs. Covers both HTTP and HTTPS proxy handling through the proxies dictionary attribute. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session(client=Client.FIREFOX_132) # Method 1: Per-request proxy response = await session.get( "https://api.ipify.org?format=json", proxy="http://username:password@proxy.example.com:8080" ) print(f"IP via proxy: {response.json()}") # Method 2: Session-wide proxy configuration session.proxies = { "http": "http://username:password@proxy.example.com:8080", "https": "http://username:password@proxy.example.com:8080" } response = await session.get("https://api.ipify.org?format=json") print(f"IP via session proxy: {response.json()}") asyncio.run(main()) ``` -------------------------------- ### Python: Perform All HTTP Methods with Noble TLS Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Provides Python code examples for executing all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) using the Noble TLS library. It demonstrates how to send request bodies, parameters, and access response status codes and headers. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session(client=Client.CHROME_131) base_url = "https://httpbin.org" # GET request resp = await session.get(f"{base_url}/get", params={"key": "value"}) print(f"GET: {resp.status_code}") # POST request resp = await session.post( f"{base_url}/post", json={"name": "John", "age": 30} ) print(f"POST: {resp.status_code}") # PUT request resp = await session.put( f"{base_url}/put", data={"field": "updated_value"} ) print(f"PUT: {resp.status_code}") # PATCH request resp = await session.patch( f"{base_url}/patch", json={"field": "partial_update"} ) print(f"PATCH: {resp.status_code}") # DELETE request resp = await session.delete(f"{base_url}/delete") print(f"DELETE: {resp.status_code}") # HEAD request (no body) resp = await session.head(f"{base_url}/get") print(f"HEAD: {resp.status_code}, Content-Type: {resp.headers.get('Content-Type')}") # OPTIONS request resp = await session.options(f"{base_url}/get") print(f"OPTIONS: {resp.status_code}, Allow: {resp.headers.get('Allow')}") asyncio.run(main()) ``` -------------------------------- ### Basic Async HTTP Get (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Demonstrate updating the TLS client library and performing an asynchronous GET request with a preset Chrome fingerprint. The code initializes a session, makes a request to an example API, and prints the response status and body. Requires asyncio for async execution and noble_tls for the session. ```python import asyncio import noble_tls from noble_tls import Client async def main(): # Auto-download/update TLS client library from GitHub await noble_tls.update_if_necessary() # Create session with preset browser fingerprint session = noble_tls.Session(client=Client.CHROME_133) # Make request response = await session.get("https://api.example.com/data") print(f"Status: {response.status_code}") print(f"Body: {response.text}") asyncio.run(main()) ``` -------------------------------- ### Install Noble TLS (Bash) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Install the Noble TLS library using pip for Python package management. This command downloads and installs the library from PyPI, enabling its use for HTTP requests with TLS fingerprinting. No additional dependencies are required in the installation process. ```bash pip install noble-tls ``` -------------------------------- ### Create TLS Session with Predefined Chrome Client (Python) Source: https://github.com/rawandahmad698/noble-tls/blob/master/README.md This snippet demonstrates how to create an asynchronous TLS session using a predefined Chrome 111 client identifier. It requires the noble_tls library and performs an update check for TLS client libraries from bogdanfinn/tls-client. The session sends a GET request with custom headers and a proxy, outputting the response text. Limitation: It only supports predefined clients and requires an async environment. ```python async def main(): await noble_tls.update_if_necessary() # Update TLS client libs from bogdanfinn/tls-client session = noble_tls.Session( client=Client.CHROME_111, random_tls_extension_order=True ) res = await session.get( "https://www.example.com/", headers={ "key1": "value1", }, proxy="http://user:password@host:port" ) print(res.text) ``` -------------------------------- ### Create Session with Preset Client (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Create a Noble TLS session using a Chrome preset, customize headers, and perform a GET request with query parameters. The session handles cookies automatically and includes timeout settings. This builds on the basic usage for more advanced request configuration. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() # Initialize session with Chrome 111 fingerprint session = noble_tls.Session( client=Client.CHROME_111, random_tls_extension_order=True, debug=False ) # Session maintains cookies automatically session.headers.update({ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Accept": "application/json" }) # GET request with query parameters response = await session.get( "https://api.example.com/search", params={"q": "python", "page": 1}, headers={"Authorization": "Bearer token123"}, timeout_seconds=10 ) print(f"Status: {response.status_code}") print(f"Response: {response.json()}") print(f"Cookies: {session.cookies.get_dict()}") asyncio.run(main()) ``` -------------------------------- ### Configure Transport Options and Connect Headers - Python Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Shows how to configure custom transport options and connect headers for noble-tls. This example demonstrates setting transport-level parameters like connection limits and timeouts, plus custom headers for CONNECT method when using proxy tunneling. Useful for proxy configurations and fine-tuning connection behavior. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session( client=Client.CHROME_131, # Custom transport options transportOptions={ "disableKeepAlives": False, "disableCompression": False, "maxIdleConns": 100, "maxIdleConnsPerHost": 10, "maxConnsPerHost": 0, "maxResponseHeaderBytes": 0, "writeBufferSize": 0, "readBufferSize": 0, "idleConnTimeout": 90 }, # Custom headers for CONNECT method (proxy tunneling) connectHeaders={ "User-Agent": "Custom-Agent/1.0", "Proxy-Authorization": "Basic base64credentials" } ) response = await session.get( "https://example.com", proxy="http://proxy.example.com:8080" ) print(f"Status: {response.status_code}") asyncio.run(main()) ``` -------------------------------- ### Configure HTTP/2 Priority Frames - Python Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Demonstrates how to configure HTTP/2 priority frames with noble-tls library. This example shows setting custom priority parameters for different streams, including weight, stream dependency, and exclusive flags. Useful for optimizing request prioritization in HTTP/2 connections. ```python import asyncio import noble_tls async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session( ja3_string="771,4865-4866-4867-49195-49199,0-23-65281-10-11-35-16-5-13-18-51-45-43-27,29-23-24,0", # Configure HTTP/2 priority frames priority_frames=[ { "streamID": 3, "priorityParam": { "weight": 201, "streamDep": 0, "exclusive": False } }, { "streamID": 5, "priorityParam": { "weight": 101, "streamDep": 0, "exclusive": False } } ], # Header priority settings header_priority={ "streamDep": 1, "exclusive": True, "weight": 1 } ) response = await session.get("https://example.com") print(f"Status: {response.status_code}") asyncio.run(main()) ``` -------------------------------- ### List Client Identifiers (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Import and list available client identifiers for various browsers and mobile apps in Noble TLS, including Chrome, Firefox, Safari, Opera, and app-specific presets. This allows selecting appropriate fingerprints for sessions. An example shows initializing a session with a Firefox identifier. ```python from noble_tls import Client # Chrome browsers (103-142) Client.CHROME_103, Client.CHROME_111, Client.CHROME_131, Client.CHROME_133 Client.CHROME_141, Client.CHROME_142 Client.CHROME_116_PSK, Client.CHROME_116_PSK_PQ # Pre-shared key variants Client.CHROME_131_PSK, Client.CHROME_133_PSK # Safari browsers Client.SAFARI_15_6_1, Client.SAFARI_16_0 Client.SAFARI_IPAD_15_6 # Safari iOS (15.5-18.0) Client.SAFARI_IOS_15_5, Client.SAFARI_IOS_15_6, Client.SAFARI_IOS_16_0 Client.SAFARI_IOS_17_0, Client.SAFARI_IOS_18_0 # Firefox browsers (102-135) Client.FIREFOX_102, Client.FIREFOX_110, Client.FIREFOX_117 Client.FIREFOX_132, Client.FIREFOX_135 # Opera browsers Client.OPERA_89, Client.OPERA_90, Client.OPERA_91 # Mobile app identifiers Client.NIKE_IOS_MOBILE, Client.NIKE_ANDROID_MOBILE Client.ZALANDO_ANDROID_MOBILE, Client.ZALANDO_IOS_MOBILE Client.MMS_IOS, Client.MMS_IOS_1, Client.MMS_IOS_2, Client.MMS_IOS_3 Client.MESH_IOS, Client.MESH_IOS_1, Client.MESH_IOS_2 Client.MESH_ANDROID, Client.MESH_ANDROID_1, Client.MESH_ANDROID_2 Client.CONFIRMED_IOS, Client.CONFIRMED_ANDROID # Android OkHttp (versions 7-13) Client.OKHTTP4_ANDROID_7, Client.OKHTTP4_ANDROID_8, Client.OKHTTP4_ANDROID_9 Client.OKHTTP4_ANDROID_10, Client.OKHTTP4_ANDROID_11, Client.OKHTTP4_ANDROID_12 Client.OKHTTP4_ANDROID_13 # Special Client.CLOUDSCRAPER # Usage example session = noble_tls.Session(client=Client.FIREFOX_135) ``` -------------------------------- ### Package Noble-TLS with Pyinstaller/Pyarmor (Linux - Ubuntu/x86) Source: https://github.com/rawandahmad698/noble-tls/blob/master/README.md Adds the tls-client-x86.so binary to the Pyinstaller or Pyarmor package for Linux Ubuntu x86 systems. This ensures the required shared object is included during the packaging process. Replace {path_to_library} with the correct path. ```bash --add-binary '{path_to_library}/tls_client/dependencies/tls-client-x86.so:tls_client/dependencies' ``` -------------------------------- ### Package Noble-TLS with Pyinstaller/Pyarmor (Linux Alpine/AMD64) Source: https://github.com/rawandahmad698/noble-tls/blob/master/README.md Adds the tls-client-amd64.so binary to the Pyinstaller or Pyarmor package for Linux Alpine AMD64 systems. This ensures the required shared object is included during the packaging process. Replace {path_to_library} with the correct path. ```bash --add-binary '{path_to_library}/tls_client/dependencies/tls-client-amd64.so:tls_client/dependencies' ``` -------------------------------- ### Package Noble-TLS with Pyinstaller/Pyarmor (Windows) Source: https://github.com/rawandahmad698/noble-tls/blob/master/README.md Adds the tls-client-64.dll binary to the Pyinstaller or Pyarmor package for Windows systems. This ensures the required dynamic-link library is included during packaging. Replace {path_to_library} with the correct path. ```bash --add-binary '{path_to_library}/tls_client/dependencies/tls-client-64.dll;tls_client/dependencies' ``` -------------------------------- ### Package Noble-TLS with Pyinstaller/Pyarmor (MacOS M1/Older) Source: https://github.com/rawandahmad698/noble-tls/blob/master/README.md Adds the tls-client-x86.dylib binary to the Pyinstaller or Pyarmor package for MacOS M1 and older systems. This ensures the required dynamic library is included during the packaging. Replace {path_to_library} with the correct path. ```bash --add-binary '{path_to_library}/tls_client/dependencies/tls-client-x86.dylib:tls_client/dependencies' ``` -------------------------------- ### Package Noble-TLS with Pyinstaller/Pyarmor (MacOS M2) Source: https://github.com/rawandahmad698/noble-tls/blob/master/README.md Adds the tls-client-arm64.dylib binary to the Pyinstaller or Pyarmor package for MacOS M2 systems. This ensures the required dynamic library is included during the packaging. Replace {path_to_library} with the correct path. ```bash --add-binary '{path_to_library}/tls_client/dependencies/tls-client-arm64.dylib:tls_client/dependencies' ``` -------------------------------- ### Create Custom TLS Session with JA3 String (Python) Source: https://github.com/rawandahmad698/noble-tls/blob/master/README.md This snippet shows how to initialize a custom TLS session by specifying detailed parameters like JA3 string, HTTP/2 settings, supported algorithms, and header orders. It depends on the noble_tls library and includes an update check for TLS client libraries. The session performs a POST request with headers and proxy, returning the response text. Limitation: Customization requires deep knowledge of TLS parameters to avoid errors in requests. ```python import noble_tls async def main(): await noble_tls.update_if_necessary() # Update TLS client libs from bogdanfinn/tls-client session = noble_tls.Session( ja3_string="771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513,29-23-24,0", h2_settings={ "HEADER_TABLE_SIZE": 65536, "MAX_CONCURRENT_STREAMS": 1000, "INITIAL_WINDOW_SIZE": 6291456, "MAX_HEADER_LIST_SIZE": 262144 }, h2_settings_order=[ "HEADER_TABLE_SIZE", "MAX_CONCURRENT_STREAMS", "INITIAL_WINDOW_SIZE", "MAX_HEADER_LIST_SIZE" ], supported_signature_algorithms=[ "ECDSAWithP256AndSHA256", "PSSWithSHA256", "PKCS1WithSHA256", "ECDSAWithP384AndSHA384", "PSSWithSHA384", "PKCS1WithSHA384", "PSSWithSHA512", "PKCS1WithSHA512", ], supported_versions=["GREASE", "1.3", "1.2"], key_share_curves=["GREASE", "X25519"], cert_compression_algo="brotli", pseudo_header_order=[ ":method", ":authority", ":scheme", ":path" ], connection_flow=15663105, header_order=[ "accept", "user-agent", "accept-encoding", "accept-language" ] ) res = await session.post( "https://www.example.com/", headers={ "key1": "value1", }, proxy="http://user:password@host:port" ) print(res.text) ``` -------------------------------- ### Debugging and Troubleshooting (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Shows enabling debug mode and panic catching to surface detailed request/response info and handle Go panics gracefully. Inputs include URLs and optional debug flags; outputs are printed diagnostics and response objects. Useful for investigating TLS fingerprinting and HTTP behavior. Limitation: debug output may be verbose; catch_panics adds overhead. ```Python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() # Enable debug mode for detailed output session = noble_tls.Session( client=Client.CHROME_131, debug=True, # Prints detailed request/response info catch_panics=True # Catches Go panic errors gracefully ) response = await session.get("https://httpbin.org/get") # Inspect response details print(f"URL: {response.url}") print(f"Status: {response.status_code}") print(f"Headers: {dict(response.headers)}") print(f"Response text:\n{response.text}") asyncio.run(main()) ``` -------------------------------- ### Session Configuration and Persistence (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Shows how to create a noble-tls Session with specific TLS client fingerprint, apply session-wide headers/params/timeouts/proxies, reuse the session across requests, and override settings per request. Inputs are URL, headers, params, timeouts, and proxies; outputs are response objects with status codes. Note: session configuration applies to all requests unless overridden on a per-request basis. ```Python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() # Create session with default headers and settings session = noble_tls.Session( client=Client.SAFARI_16_0, random_tls_extension_order=True ) # Configure session-wide headers session.headers.update({ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)", "Accept": "application/json, text/plain, */*", "Accept-Language": "en-US,en;q=0.9", "Referer": "https://example.com" }) # Configure default query parameters session.params = {"api_key": "your_key", "format": "json"} # Set default timeout session.timeout_seconds = 30 # Configure proxies session.proxies = { "http": "http://proxy.example.com:8080", "https": "http://proxy.example.com:8080" } # All requests use session configuration response1 = await session.get("https://api.example.com/users") print(f"Request 1: {response1.status_code}") # Override session settings per request response2 = await session.get( "https://api.example.com/admin", headers={"Authorization": "Bearer admin_token"}, params={"detailed": "true"}, timeout_seconds=60, proxy=None # Disable proxy for this request ) print(f"Request 2: {response2.status_code}") asyncio.run(main()) ``` -------------------------------- ### Auto-Updating TLS Client Library (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Covers checking/downloading missing dependencies and updating to the latest tls-client library version from GitHub. Shows platform-specific library locations for Linux, macOS (Intel/ARM), and Windows. Inputs are platform detection and network availability; outputs are downloaded binaries and a working Session. Limitation: requires network access to GitHub; may need permission to write to dependencies directory. ```Python import asyncio import noble_tls async def main(): # Check and download if dependencies are missing await noble_tls.download_if_necessary() # Update to latest version from GitHub (bogdanfinn/tls-client) await noble_tls.update_if_necessary() # Libraries auto-downloaded to: noble_tls/dependencies/ # Platform-specific files: # - Linux Ubuntu: tls-client-linux-ubuntu-amd64-{version}.so # - macOS Intel: tls-client-darwin-amd64-{version}.dylib # - macOS M1/M2: tls-client-darwin-arm64-{version}.dylib # - Windows: tls-client-win32-64-{version}.dll session = noble_tls.Session(client=noble_tls.Client.CHROME_133) response = await session.get("https://example.com") print(f"Status: {response.status_code}") asyncio.run(main()) ``` -------------------------------- ### Python: Handle HTTP Redirects with Noble TLS Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Demonstrates how to manage HTTP redirects using the Noble TLS library. It shows how to allow redirects by default and how to disable them to inspect redirect chains and headers. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session( client=Client.NIKE_IOS_MOBILE, debug=True ) # URL shortener that redirects response = await session.get( "https://bit.ly/3K5GY8J", allow_redirects=True ) print(f"Final Status: {response.status_code}") print(f"Final URL: {response.url}") # Examine redirect chain print(f"\nRedirect chain ({len(response.history)} redirects):") for i, hist in enumerate(response.history, 1): print(f" {i}. {hist.url} -> {hist.status_code}") # Disable redirects response_no_redirect = await session.get( "https://bit.ly/3K5GY8J", allow_redirects=False ) print(f"\nWithout redirect: {response_no_redirect.status_code}") print(f"Location header: {response_no_redirect.headers.get('Location')}") asyncio.run(main()) ``` -------------------------------- ### Custom TLS Configuration with Noble TLS Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Shows advanced TLS fingerprinting configuration using noble-tls library. Covers JA3 fingerprint strings, HTTP/2 settings, signature algorithms, TLS versions, key share curves, certificate compression, header ordering, and various connection options. Demonstrates full control over TLS handshake parameters for bypassing security detection. ```python import asyncio import noble_tls async def main(): await noble_tls.update_if_necessary() # Full custom TLS fingerprint session = noble_tls.Session( # JA3 fingerprint string ja3_string="771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513,29-23-24,0", # HTTP/2 settings h2_settings={ "HEADER_TABLE_SIZE": 65536, "MAX_CONCURRENT_STREAMS": 1000, "INITIAL_WINDOW_SIZE": 6291456, "MAX_HEADER_LIST_SIZE": 262144 }, h2_settings_order=[ "HEADER_TABLE_SIZE", "MAX_CONCURRENT_STREAMS", "INITIAL_WINDOW_SIZE", "MAX_HEADER_LIST_SIZE" ], # TLS signature algorithms supported_signature_algorithms=[ "ECDSAWithP256AndSHA256", "PSSWithSHA256", "PKCS1WithSHA256", "ECDSAWithP384AndSHA384", "PSSWithSHA384", "PKCS1WithSHA384", "PSSWithSHA512", "PKCS1WithSHA512" ], # TLS versions supported_versions=["GREASE", "1.3", "1.2"], # Key share curves key_share_curves=["GREASE", "X25519"], # Certificate compression cert_compression_algo="brotli", # HTTP/2 pseudo-header order pseudo_header_order=[":method", ":authority", ":scheme", ":path"], # Connection flow window size connection_flow=15663105, # Custom header ordering header_order=["accept", "user-agent", "accept-encoding", "accept-language"], # Additional options random_tls_extension_order=True, force_http1=False, catch_panics=True, debug=False ) response = await session.get("https://example.com") print(f"Status: {response.status_code}") asyncio.run(main()) ``` -------------------------------- ### POST Form Data Request with Noble TLS Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Demonstrates making POST requests with form-encoded data using noble-tls library. Shows how to update library, create sessions with specific client fingerprints, send form data including multi-valued parameters, and handle responses. Requires noble-tls library and asyncio for async operations. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session(client=Client.SAFARI_IOS_17_0) # POST with form-encoded data response = await session.post( "https://example.com/submit", data={ "name": "John Doe", "email": "john@example.com", "message": "Hello World", "tags": ["python", "automation"] # Multivalued parameters }, headers={ "Referer": "https://example.com/form" } ) print(f"Status: {response.status_code}") print(f"Response: {response.text}") asyncio.run(main()) ``` -------------------------------- ### Cookie Management with Noble TLS Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Shows comprehensive cookie management using noble-tls library. Demonstrates automatic cookie handling from responses, cookie persistence across requests, manual cookie setting with domain specification, per-request cookie merging, and cookie inspection. Covers both session-level and request-level cookie operations. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session(client=Client.CHROME_133) # First request sets cookies response1 = await session.get("https://httpbin.org/cookies/set?session=abc123") print(f"Cookies after first request: {session.cookies.get_dict()}") # Cookies automatically sent on subsequent requests response2 = await session.get("https://httpbin.org/cookies") print(f"Server received cookies: {response2.json()}") # Access individual cookies for cookie in session.cookies: print(f"{cookie.name}={cookie.value} (domain: {cookie.domain})") # Manually set cookies session.cookies.set("custom_cookie", "custom_value", domain=".example.com") # Per-request cookies (merged with session cookies) response3 = await session.get( "https://example.com", cookies={"temp_token": "xyz789"} ) asyncio.run(main()) ``` -------------------------------- ### Binary Request and Byte Response Handling (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Demonstrates sending binary payloads with Content-Type: application/octet-stream and receiving byte responses for non-text content. Use is_byte_response=True to return bytes directly; access content via response.content. Inputs are URLs and binary payloads; outputs are response objects and raw bytes. Limitation: requires correct Content-Type and client fingerprint compatibility for some endpoints. ```Python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session(client=Client.CHROME_131) # Send binary data binary_payload = b'\x00\x01\x02\x03\x04\x05' response = await session.post( "https://httpbin.org/post", data=binary_payload, headers={"Content-Type": "application/octet-stream"}, is_byte_response=True ) print(f"Status: {response.status_code}") # Download binary content (image, PDF, etc.) img_response = await session.get( "https://httpbin.org/image/png", is_byte_response=True ) # Access as bytes image_data = img_response.content print(f"Downloaded {len(image_data)} bytes") # Save to file with open("downloaded.png", "wb") as f: f.write(image_data) asyncio.run(main()) ``` -------------------------------- ### Python: Error Handling and Response Processing with Noble TLS Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Illustrates robust error handling and response processing in Python using Noble TLS. It covers handling HTTP errors, specific library exceptions, and general exceptions, along with accessing response details like JSON data, headers, and content. ```python import asyncio import noble_tls from noble_tls import Client from noble_tls.exceptions import TLSClientException from requests.exceptions import HTTPError async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session(client=Client.CHROME_131) try: response = await session.get( "https://api.example.com/data", timeout_seconds=5 ) # Raise exception for 4xx/5xx status codes response.raise_for_status() # Process successful response data = response.json() print(f"Data: {data}") # Access response properties print(f"Status: {response.status_code}") print(f"Headers: {dict(response.headers)}") print(f"Cookies: {response.cookies.get_dict()}") # Access raw bytes content_bytes = response.content print(f"Content length: {len(content_bytes)} bytes") except HTTPError as e: print(f"HTTP Error: {e}") except TLSClientException as e: print(f"TLS Client Error: {e}") except Exception as e: print(f"Unexpected error: {e}") asyncio.run(main()) ``` -------------------------------- ### POST Request with JSON Payload (Python) Source: https://context7.com/rawandahmad698/noble-tls/llms.txt Perform a POST request with a JSON body for logging in, handling the response and session cookies. The code checks the status code, parses JSON if successful, and raises an error otherwise. Utilizes noble_tls for fingerprinting and async requests. ```python import asyncio import noble_tls from noble_tls import Client async def main(): await noble_tls.update_if_necessary() session = noble_tls.Session(client=Client.CHROME_131) # POST with JSON body response = await session.post( "https://api.example.com/login", json={ "username": "user@example.com", "password": "secure_password", "remember": True }, headers={ "Content-Type": "application/json", "X-API-Key": "your-api-key" } ) if response.status_code == 200: data = response.json() print(f"Login successful: {data}") print(f"Session cookies: {response.cookies}") else: response.raise_for_status() asyncio.run(main()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.