### Execute JS Instructions and Get Report Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This example demonstrates executing custom JavaScript instructions on a webpage and retrieving a report on their execution status. The report includes counts of executed and failed instructions. ```ruby response = api.get(url, js_instructions: instructions, json_response: true) puts response.js_instructions_report # => {"executed" => 5, "failed" => 0, "details" => [...]} ``` -------------------------------- ### Install Zenrows Ruby Gem Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Instructions on how to add the Zenrows gem to your project's Gemfile and install it using Bundler. ```ruby gem 'zenrows' ``` ```bash bundle install ``` -------------------------------- ### Basic Zenrows HTTP Request Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Example of making a basic GET request using the Zenrows client, enabling JavaScript rendering and using premium proxies. ```ruby client = Zenrows::Client.new http = client.http(js_render: true, premium_proxy: true) response = http.get('https://example.com', ssl_context: client.ssl_context) puts response.body puts response.status ``` -------------------------------- ### Install Dependencies and Run Commands (Bash) Source: https://github.com/swistaczek/zenrows-rb/blob/main/CLAUDE.md This snippet shows essential bash commands for managing the Zenrows-rb gem project. It includes installing dependencies with `bundle install`, running tests, linting code, generating documentation, and building the gem. ```bash bundle install # Install dependencies bundle exec rake test # Run tests bundle exec rubocop # Lint code bundle exec yard doc # Generate docs bundle exec rake build # Build gem ``` -------------------------------- ### Zenrows Development Commands Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Common commands for developing the Zenrows Ruby client, including installing dependencies, running tests, linting, and generating documentation. ```bash bundle install bundle exec rake test # Run tests bundle exec standardrb # Lint code bundle exec yard doc # Generate docs ``` -------------------------------- ### Configure ZenRows Client and Make HTTP Requests in Ruby Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Demonstrates how to configure the ZenRows client with an API key and other settings, and then use the client to make HTTP GET requests. It shows examples of simple proxy usage, advanced options like JS rendering and waiting for specific elements, and how to handle the response object. ```ruby # Configuration Zenrows.configure do |config| config.api_key = 'YOUR_API_KEY' config.host = 'superproxy.zenrows.com' # from credentials config.port = 1337 config.default_timeout = 180 config.backend = :http_rb # :faraday, :net_http (future) end # Get pre-configured HTTP client (proxy mode) client = Zenrows::Client.new # Simple proxy client http = client.http(js_render: true, premium_proxy: true) response = http.get('https://example.com') # With full options http = client.http( js_render: true, premium_proxy: true, proxy_country: 'us', wait: 5000, # ms or ActiveSupport::Duration wait_for: '.content', # CSS selector session_id: true # sticky session ) response = http.get(url) # Response handling response.body # HTML string response.status # HTTP status response.headers # Response headers (includes Zr-* headers) response.final_url # From Zr-Final-Url header response.cookies # From Zr-Cookies header # JS Instructions DSL (optional) instructions = Zenrows::JsInstructions.build do click '.load-more' wait 2000 fill 'input#email', 'test@example.com' scroll_to :bottom wait_for '.results' end http = client.http(js_render: true, js_instructions: instructions) # SSL context (auto-configured, verify_mode: NONE for proxy) # Timeouts auto-calculated based on js_render + wait options ``` -------------------------------- ### Configure Zenrows-rb Client (Ruby) Source: https://github.com/swistaczek/zenrows-rb/blob/main/CLAUDE.md This Ruby code demonstrates how to configure the Zenrows-rb client with API key, host, and port. It then shows how to instantiate the client and make an HTTP GET request, enabling JavaScript rendering and premium proxy options. The `ssl_context` is passed from the client. ```ruby Zenrows.configure do |c| c.api_key = 'YOUR_KEY' c.host = 'superproxy.zenrows.com' c.port = 1337 end client = Zenrows::Client.new http = client.http(js_render: true, premium_proxy: true) response = http.get('https://example.com', ssl_context: client.ssl_context) ``` -------------------------------- ### Execute JavaScript Instructions and Capture Screenshot Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This example uses `js_instructions` to automate browser actions like waiting for elements, scrolling, and clicking before capturing a full-page screenshot. It requires the `zenrows` gem. ```ruby require 'zenrows' api = Zenrows::ApiClient.new url = "YOUR_URL_HERE" instructions = Zenrows::JsInstructions.build do wait_for '.content-loaded' scroll_to :bottom wait 1000 click '.expand-details' wait 500 end response = api.get( url, js_render: true, js_instructions: instructions, screenshot: true, screenshot_fullpage: true, json_response: true ) ``` -------------------------------- ### Zenrows JavaScript Instructions Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Example of using Zenrows' JsInstructions to automate browser interactions like filling forms, clicking elements, and scrolling. ```ruby instructions = Zenrows::JsInstructions.build do wait_for '.login-form' fill '#email', 'user@example.com' fill '#password', 'secret123' click '#submit' wait 2000 scroll_to :bottom wait_for '.results' end http = client.http(js_render: true, js_instructions: instructions) response = http.get(url, ssl_context: client.ssl_context) ``` -------------------------------- ### Zenrows Block Resources Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Example of configuring Zenrows to block specific resource types (images, media, fonts) to speed up requests. ```ruby http = client.http( js_render: true, block_resources: 'image,media,font' ) ``` -------------------------------- ### Get Markdown Response with Specific Outputs (Ruby) Source: https://context7.com/swistaczek/zenrows-rb/llms.txt Demonstrates how to fetch web content in markdown format and extract specific elements like headings and links using the ZenRows Ruby client. This is useful for content scraping where structured text is preferred. ```ruby response = api.get( url, response_type: 'markdown', outputs: 'headings,links' ) ``` -------------------------------- ### YARD Documentation Standards for Ruby Methods Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Shows the standard YARD tags used for documenting Ruby methods within the ZenRows project. This includes tags for author, version, API visibility, parameters, options, return values, exceptions, and examples, promoting consistent and informative documentation. ```ruby # @author Ernest Surudo # @since 1.0.0 # @api public # @param url [String] Target URL to scrape # @param options [Hash] Request options # @option options [Boolean] :js_render Enable JavaScript rendering # @option options [Boolean] :premium_proxy Use residential proxies # @option options [String] :proxy_country ISO country code (us, gb, de) # @option options [Integer] :wait Wait time in milliseconds # @option options [String] :wait_for CSS selector to wait for # @return [Zenrows::Response] Response object # @raise [Zenrows::Error] Base error class # @raise [Zenrows::RateLimitError] When rate limited (429) # @raise [Zenrows::AuthenticationError] Invalid API key # @example Basic request # client.get('https://example.com') # @example With JavaScript rendering # client.get('https://example.com', js_render: true, wait: 5000) def get(url, options = {}) end ``` -------------------------------- ### Define Base Backend Interface in Ruby Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Defines the abstract base class for ZenRows backends, establishing the interface for HTTP GET and POST requests. Concrete implementations must override these methods. It serves as a blueprint for different HTTP client integrations. ```ruby module Zenrows module Backends class Base def get(url, options = {}) raise NotImplementedError end def post(url, body, options = {}) raise NotImplementedError end end class HttpRb < Base # Primary backend using http.rb gem # Supports: proxy, ssl_context, timeouts, headers end end end ``` -------------------------------- ### Initialize Ruby Gem Project with Bundler and RSpec in Bash Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md This command demonstrates how to bootstrap a new Ruby gem project using Bundler. It sets up the basic project structure, including RSpec for testing, GitHub Actions for CI, and RuboCop for linting, providing a solid foundation for gem development. ```bash bundle gem zenrows --test=rspec --ci=github --linter=rubocop ``` -------------------------------- ### Zenrows Request with Options Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Demonstrates making a Zenrows request with various options including JavaScript rendering, premium proxies, geolocation, wait times, and session persistence. ```ruby http = client.http( js_render: true, # Enable headless browser premium_proxy: true, # Use residential IPs proxy_country: 'us', # Geolocation wait: 5000, # Wait 5 seconds after load wait_for: '.content', # Wait for CSS selector session_id: true # Sticky session ) ``` -------------------------------- ### Zenrows Configuration and Client Usage Source: https://github.com/swistaczek/zenrows-rb/blob/main/CLAUDE.md This section details how to configure the ZenRows client with your API key and host, and how to instantiate the client to make HTTP requests with various rendering and proxy options. ```APIDOC ## Zenrows Configuration and Client Usage ### Description Configure the ZenRows client with your API key, host, and port. Then, instantiate the client to obtain an HTTP instance that can be used to make requests to ZenRows. ### Method ```ruby Zenrows.configure do |c| c.api_key = 'YOUR_KEY' c.host = 'superproxy.zenrow s.com' c.port = 1337 end client = Zenrows::Client.new http = client.http(js_render: true, premium_proxy: true) response = http.get('https://example.com', ssl_context: client.ssl_context) ``` ### Key Options for `client.http` Method | Option | Type | Description | |--------|------|-------------| | `js_render` | Boolean | Enable headless browser | | `premium_proxy` | Boolean | Use residential IPs | | `proxy_country` | String | Country code (us, gb, de) | | `wait` | Integer | Wait time in ms | | `wait_for` | String | CSS selector to wait for | | `js_instructions` | Array/JSON | Browser automation | | `session_id` | Bool/String | Sticky session | | `screenshot` | Boolean | Take screenshot | ### Request Example (Conceptual) ```json { "url": "https://example.com", "options": { "js_render": true, "premium_proxy": true, "proxy_country": "us", "wait": 5000, "wait_for": ".some-selector", "js_instructions": [ "click .login-button", "fill "#username" with "testuser"" ], "session_id": "unique_session_id", "screenshot": true } } ``` ### Response Example (Conceptual) ```json { "status": 200, "body": "...", "headers": { ... }, "screenshot": "base64_encoded_image" } ``` ``` -------------------------------- ### Screenshot and Device Emulation Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This section details how to capture screenshots of web pages, including full page and specific element screenshots. It also covers emulating various devices like mobile and desktop with custom dimensions, and integrating browser automation for dynamic content. ```APIDOC ## GET /api/v1 ### Description Captures screenshots of web pages, emulates devices, and allows for browser automation. ### Method GET ### Endpoint /api/v1 ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the web page to scrape. - **screenshot** (boolean) - Optional - Whether to capture a screenshot. Defaults to false. - **screenshot_fullpage** (boolean) - Optional - Whether to capture a full page screenshot. Defaults to false. - **screenshot_selector** (string) - Optional - CSS selector to capture a specific element's screenshot. - **js_render** (boolean) - Optional - Whether to render JavaScript on the page. Defaults to false. - **device** (string) - Optional - Emulates a device. Options: 'mobile', 'desktop'. - **window_width** (integer) - Optional - Sets the browser window width. - **window_height** (integer) - Optional - Sets the browser window height. - **js_instructions** (string) - Optional - JavaScript instructions to execute on the page. - **json_response** (boolean) - Optional - Whether to return the response as JSON. Defaults to false. ### Request Example ```json { "url": "https://example.com", "screenshot": true, "screenshot_fullpage": true, "js_render": true, "device": "mobile", "window_width": 375, "window_height": 812, "js_instructions": "wait_for '.content-loaded'; scroll_to :bottom; click '.expand-details';", "json_response": true } ``` ### Response #### Success Response (200) - **screenshot** (string) - Base64 encoded image data if `screenshot` is true. - **js_instructions_report** (object) - Report on executed JS instructions if `js_instructions` is used. #### Response Example ```json { "screenshot": "iVBORw0KGgoAAAANSUhEUgAA...", "js_instructions_report": { "executed": 3, "failed": 0 } } ``` ``` -------------------------------- ### Configure Zenrows Client Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Code snippet demonstrating how to configure the Zenrows client with your API key and other connection settings like host, port, and timeouts. ```ruby Zenrows.configure do |config| config.api_key = 'YOUR_API_KEY' config.host = 'superproxy.zenrows.com' # default config.port = 1337 # default config.connect_timeout = 5 # seconds config.read_timeout = 180 # seconds end ``` -------------------------------- ### Emulate Desktop with Custom Dimensions Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This code demonstrates scraping a website with JavaScript rendering enabled, emulating a desktop browser with custom window dimensions. ```ruby require 'zenrows' api = Zenrows::ApiClient.new url = "YOUR_URL_HERE" response = api.get( url, js_render: true, device: 'desktop', window_width: 1920, window_height: 1080 ) ``` -------------------------------- ### Configure Proxy and Timeouts with http.rb in Ruby Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Illustrates advanced usage patterns for the http.rb gem, focusing on network configurations. This includes setting up proxy connections with authentication, defining custom proxy headers, and managing operation-specific or global timeouts for requests. ```ruby # Proxy with auth HTTP.via("proxy-hostname", 8080, "username", "password") .get("http://example.com") # Custom proxy headers HTTP.via("proxy-hostname", 8080, {"Proxy-Authorization" => "..."}) .get("http://example.com") # Timeouts (per-operation) HTTP.timeout(connect: 5, write: 2, read: 10).get(url) # Global timeout HTTP.timeout(30).get(url) # SSL contextssl_context = OpenSSL::SSL::SSLContext.newssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE HTTP.get(url, ssl_context: ssl_context) # Headers HTTP.headers("User-Agent" => "...", "Accept" => "...").get(url) ``` -------------------------------- ### Capture Screenshot and Save as PNG Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This snippet demonstrates how to capture a full page screenshot of a URL and save it as a PNG file. It uses the `screenshot` and `screenshot_fullpage` parameters and decodes the Base64 response. ```ruby require 'zenrows' require 'base64' api = Zenrows::ApiClient.new response = api.get( 'https://example.com', screenshot: true, screenshot_fullpage: true, json_response: true ) File.write('page.png', Base64.decode64(response.screenshot)) ``` -------------------------------- ### Zenrows Error Handling Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Demonstrates how to handle various Zenrows exceptions, including configuration errors, rate limits, bot detection, and timeouts, with retry mechanisms. ```ruby begin response = http.get(url, ssl_context: client.ssl_context) rescue Zenrows::ConfigurationError => e # Missing or invalid configuration rescue Zenrows::RateLimitError => e sleep(e.retry_after || 60) retry rescue Zenrows::BotDetectedError => e # Try with premium proxy http = client.http(premium_proxy: true, proxy_country: 'us') retry rescue Zenrows::WaitTimeError => e # Wait time exceeded 3 minutes rescue Zenrows::TimeoutError => e # Request timed out end ``` -------------------------------- ### Output Formats and Structured Data Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This section describes how to extract specific data types from web pages using the `outputs` parameter, allowing you to retrieve structured information such as headings, links, images, menus, and tables directly. ```APIDOC ## Output formats and structured data ### Description Extract specific data types with the `outputs` parameter. ### Method GET ### Endpoint /api/v1 ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the web page. - **outputs** (string) - Required - Comma-separated list of data types to extract. Available: `headings`, `links`, `images`, `menus`, `tables`. ### Request Example ```ruby require 'zenrows' api = Zenrows::ApiClient.new response = api.get( 'https://example.com/article', outputs: 'headings,links,menus' ) puts response.data ``` ### Response #### Success Response (200) - **data** (object) - An object containing the requested structured data. #### Response Example ```json { "headings": ["Title", "Subtitle", ...], "links": [{"text": "...", "href": "..."}, ...], "menus": [{"name": "...", "items": [...]}] } ``` ``` -------------------------------- ### Build and Execute JavaScript Instructions for Browser Automation with Zenrows::JsInstructions Source: https://context7.com/swistaczek/zenrows-rb/llms.txt Zenrows::JsInstructions provides a Domain Specific Language (DSL) for automating browser interactions during page rendering. It allows you to define a sequence of actions like waiting for elements, filling forms, clicking buttons, scrolling, and executing custom JavaScript. These instructions can then be used with Zenrows::Client or Zenrows::ApiClient for headless browser automation. Dependencies include the 'zenrows' gem. ```ruby require 'zenrows' # Build JavaScript instructions instructions = Zenrows::JsInstructions.build do # Wait for and interact with login form wait_for '.login-form' fill '#email', 'user@example.com' fill '#password', 'secret123' click '#submit-button' # Wait for page load wait 2000 wait_event :networkidle # Scroll to load dynamic content scroll_to :bottom wait 1000 # Click "Load More" button multiple times click '.load-more' wait 1500 click '.load-more' # Wait for results wait_for '.results-loaded' # Execute custom JavaScript evaluate "document.querySelector('.popup')?.remove()" end # Use with Client client = Zenrows::Client.new http = client.http( js_render: true, js_instructions: instructions ) response = http.get('https://example.com', ssl_context: client.ssl_context) # Use with ApiClient api = Zenrows::ApiClient.new response = api.get( 'https://example.com', js_render: true, js_instructions: instructions ) # Form interactions instructions = Zenrows::JsInstructions.build do # Checkboxes and select dropdowns check '#terms-checkbox' uncheck '#newsletter-checkbox' select_option '#country-select', 'US' # Scrolling scroll_y 1500 # Scroll down 1500px scroll_x 200 # Scroll right 200px scroll_to :top # Scroll to top # Wait for events wait_event :domcontentloaded wait_event :load wait_event :networkidle end # Iframe interactions instructions = Zenrows::JsInstructions.build do frame_wait_for 'iframe#payment', '.card-form' frame_fill 'iframe#payment', '#card-number', '4242424242424242' frame_click 'iframe#payment', '#submit' frame_evaluate 'iframe#payment', 'console.log("Form submitted")' end # Convert to JSON for manual use json_str = instructions.to_json # => '[{"wait_for":".login-form"},{"fill":["#email","user@example.com"]}]' ``` -------------------------------- ### Emulate Mobile Device for Web Scraping Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This snippet shows how to scrape a website while emulating a mobile device. It enables JavaScript rendering and sets specific window dimensions for a mobile view. ```ruby require 'zenrows' api = Zenrows::ApiClient.new url = "YOUR_URL_HERE" response = api.get( url, js_render: true, device: 'mobile', window_width: 375, window_height: 812 ) ``` -------------------------------- ### Zenrows Rails Integration with Duration Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Shows how the Zenrows gem integrates with Rails, using Rails logger by default and supporting ActiveSupport::Duration for wait times. ```ruby # In Rails, you can use duration objects http = client.http(wait: 5.seconds) ``` -------------------------------- ### Autoparse E-commerce Data with ZenRows (Ruby) Source: https://context7.com/swistaczek/zenrows-rb/llms.txt Shows how to use the ZenRows Ruby client with the autoparse feature to automatically extract structured product data, images, and links from an e-commerce URL. The parsed data is then printed to the console. ```ruby response = api.get( 'https://amazon.com/dp/B01LD5GO7I', autoparse: true, outputs: 'images,links' ) puts response.parsed # => Full product data + extracted images and links ``` -------------------------------- ### ZenRows Ruby Gem - Helper Methods Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Describes utility methods provided by the gem for tasks such as building proxy URLs, handling SSL contexts, and resolving DNS. ```APIDOC ## ZenRows Helper Methods ### Description These are utility methods provided by the ZenRows Ruby gem to assist with various aspects of request construction and network management. ### Method Ruby method calls ### Endpoint N/A (Client-side Ruby methods) ### Helper Methods - **`zenrows_ssl_context`**: - Description: Generates an SSL context, typically configured with `verify_mode: NONE`. - Usage: `ZenrowsHelper.zenrows_ssl_context` - **`http_zenrows_proxy_url(opts)`**: - Description: Constructs the HTTP proxy URL based on provided options. - Parameters: - `opts` (Hash) - Options for proxy configuration. - Usage: `ZenrowsHelper.http_zenrows_proxy_url(opts)` - **`http_zenrows_proxy_array(opts)`**: - Description: Returns the proxy details as an array `[host, port, user, pass]`. - Parameters: - `opts` (Hash) - Options for proxy configuration. - Usage: `ZenrowsHelper.http_zenrows_proxy_array(opts)` - **`wss_zenrows_proxy_url(opts)`**: - Description: Constructs the WebSocket proxy URL based on provided options. - Parameters: - `opts` (Hash) - Options for proxy configuration. - Usage: `ZenrowsHelper.wss_zenrows_proxy_url(opts)` - **`ensure_dns_resolved(url, opts)`**: - Description: Pre-resolves DNS for a given URL with caching enabled. - Parameters: - `url` (String) - The URL to resolve. - `opts` (Hash) - Options for DNS resolution. - Usage: `ZenrowsHelper.ensure_dns_resolved(url, opts)` ### Request Example ```ruby # Example for building a proxy URL proxy_options = { premium_proxy: true, proxy_country: 'us' } proxy_url = ZenrowsHelper.http_zenrows_proxy_url(proxy_options) puts "Proxy URL: #{proxy_url}" # Example for DNS resolution url_to_resolve = "https://example.com" resolved_data = ZenrowsHelper.ensure_dns_resolved(url_to_resolve, {}) puts "DNS Resolved: #{resolved_data.inspect}" ``` ### Response #### Success Response - **`zenrows_ssl_context`**: Returns an OpenSSL::SSL::SSLContext object. - **`http_zenrows_proxy_url` / `wss_zenrows_proxy_url`**: Returns a String representing the proxy URL. - **`http_zenrows_proxy_array`**: Returns an Array of strings `[host, port, user, pass]`. - **`ensure_dns_resolved`**: Returns resolved DNS information (e.g., IP addresses). ``` -------------------------------- ### Extract Specific Data Outputs from Webpage Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This code snippet shows how to specify the type of data to extract from a webpage using the `outputs` parameter. It demonstrates extracting headings, links, and menus, with the results available in `response.data`. ```ruby require 'zenrows' api = Zenrows::ApiClient.new # Extract specific outputs response = api.get( 'https://example.com/article', outputs: 'headings,links,menus' ) puts response.data # => { # "headings" => ["Title", "Subtitle", ...], # "links" => [{"text" => "...", "href" => "..."}, ...], # "menus" => [{"name" => "...", "items" => [...]}] # } # Available outputs: headings, links, images, menus, tables ``` -------------------------------- ### Configure Zenrows Ruby Client Source: https://context7.com/swistaczek/zenrows-rb/llms.txt Sets up global configuration for the ZenRows Ruby client, including API key and proxy details. It allows validation and resetting of configurations to default settings. Essential for authenticating requests to the ZenRows service. ```ruby Zenrows.configure do |config| config.api_key = 'YOUR_API_KEY' config.host = 'superproxy.zenrows.com' # default config.port = 1337 # default config.connect_timeout = 5 # seconds config.read_timeout = 180 # seconds end # Check if configuration is valid if Zenrows.configuration.valid? puts "Configuration OK" end # Reset to defaults Zenrows.reset_configuration! ``` -------------------------------- ### Advanced Session Management Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This section explains how to manage sessions for consistent IP addresses across multiple requests. It covers auto-generated and custom session IDs, session time-to-live (TTL) settings, and configuring different proxy countries per session. ```APIDOC ## Advanced Session Management ### Description Maintains consistent IP addresses across requests using session IDs. ### Method HTTP client configuration ### Parameters - **premium_proxy** (boolean) - Required - Use premium proxies. - **session_id** (boolean or string) - Required - Set to `true` for auto-generated session ID or provide a custom string. - **session_ttl** (string) - Required - Duration for the session. Examples: '30s', '5m', '30m', '1h', '1d'. - **proxy_country** (string) - Optional - Specify the country for the proxy. ### Request Example ```ruby require 'zenrows' client = Zenrows::Client.new # Auto-generated session ID for 30 minutes http = client.http( premium_proxy: true, session_id: true, session_ttl: '30m' ) response1 = http.get('https://site.com/page1', ssl_context: client.ssl_context) response2 = http.get('https://site.com/page2', ssl_context: client.ssl_context) # Both requests use the same IP address. # Custom session ID for 1 day session_id = "user_123_#{Time.now.to_i}" http = client.http( premium_proxy: true, session_id: session_id, session_ttl: '1d' ) # Different proxy countries per session http_us = client.http( premium_proxy: true, proxy_country: 'us', session_id: 'us_session', session_ttl: '30m' ) http_gb = client.http( premium_proxy: true, proxy_country: 'gb', session_id: 'gb_session', session_ttl: '30m' ) ``` ``` -------------------------------- ### ZenRows Ruby Gem - JavaScript Instructions Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Details the structure and capabilities of `js_instructions` for advanced browser automation within the ZenRows gem. ```APIDOC ## ZenRows JavaScript Instructions ### Description The `js_instructions` parameter allows for detailed control over browser actions when using the headless browser feature (`js_render: true`). These instructions are provided as a JSON array, enabling complex automation sequences. ### Method Parameter within `zenrows_http_client` call. ### Endpoint N/A (Client-side Ruby method parameter) ### Supported Instructions - **`wait`**: Wait for a specified duration (in milliseconds). - Example: `{"type": "wait", "duration": 3000}` - **`wait_for`**: Wait until a specific CSS selector appears on the page. - Example: `{"type": "wait_for", "selector": ".my-element"}` - **`wait_event`**: Wait for a specific network or page load event. - Supported events: `networkidle`, `load`, `domcontentloaded`. - Example: `{"type": "wait_event", "event": "networkidle"}` - **`click`**: Simulate a click on a specified CSS selector. - Example: `{"type": "click", "selector": "#submit-button"}` - **`fill`**: Fill an input field identified by a CSS selector with given text. - Example: `{"type": "fill", "selector": "input[name='email']", "text": "test@example.com"}` - **`check` / `uncheck`**: Check or uncheck a checkbox or radio button. - Example: `{"type": "check", "selector": "input[type='checkbox']"}` - **`select_option`**: Select an option from a dropdown. - Example: `{"type": "select_option", "selector": "select[name='country']", "option": "USA"}` - **`scroll_y` / `scroll_x`**: Scroll the page vertically or horizontally by a specified number of pixels. - Example: `{"type": "scroll_y", "pixels": 500}` - **`scroll_to`**: Scroll to the top or bottom of the page. - Example: `{"type": "scroll_to", "direction": "bottom"}` - **`evaluate`**: Execute custom JavaScript code. - Example: `{"type": "evaluate", "code": "document.title"}` - **`frame_*`**: Interact with elements within iframes (e.g., `frame_click`, `frame_fill`). Requires specifying the frame index or name. - Example: `{"type": "frame_click", "frame": 0, "selector": "#inner-button"}` - **`solve_captcha`**: Attempt to solve CAPTCHAs. - Example: `{"type": "solve_captcha"}` ### Request Example ```ruby instructions = [ { type: 'wait_for', selector: '.product-list' }, { type: 'scroll_to', direction: 'bottom' }, { type: 'wait', duration: 2000 }, { type: 'click', selector: '#load-more-button' }, { type: 'evaluate', code: 'return document.querySelector("body").scrollHeight;' } ] response = client.zenrows_http_client({ url: 'https://example.com/products', js_render: true, js_instructions: instructions }) ``` ### Response #### Success Response (200) - **`body`** (String) - The content of the page after executing JavaScript instructions. This could be HTML, JSON, or screenshot data depending on other parameters. - **`status`** (Integer) - The HTTP status code. - **`headers`** (Hash) - The HTTP headers. #### Response Example (assuming `json_response: true`) ```json { "product_count": 50, "status": 200, "headers": { ... } } ``` ``` -------------------------------- ### Error Handling Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This section outlines the various exception types that can be raised by the ZenRows client, providing details on how to handle specific error conditions such as configuration issues, authentication failures, rate limiting, bot detection, and timeouts. ```APIDOC ## Error Handling ### Description Handles various exceptions that may occur during API requests. ### Exception Types - **Zenrows::ConfigurationError**: Missing or invalid API key. - **Zenrows::AuthenticationError**: Invalid API key (HTTP 401). - **Zenrows::RateLimitError**: Rate limited (HTTP 429). Contains `retry_after` attribute. - **Zenrows::BotDetectedError**: Bot detection triggered (HTTP 403). Contains `suggestion` attribute. - **Zenrows::WaitTimeError**: Wait time exceeds limit. - **Zenrows::TimeoutError**: Request timed out. - **Zenrows::ProxyError**: Proxy connection failed. - **Zenrows::Error**: Generic ZenRows error. ### Request Example ```ruby require 'zenrows' begin client = Zenrows::Client.new http = client.http(js_render: true) response = http.get(url, ssl_context: client.ssl_context) rescue Zenrows::RateLimitError => e puts "Rate limited. Retry after: #{e.retry_after} seconds" sleep(e.retry_after || 60) retry rescue Zenrows::BotDetectedError => e puts "Bot detected: #{e.message}" puts "Suggestion: #{e.suggestion}" # Retry with premium proxy http = client.http( premium_proxy: true, proxy_country: 'us', antibot: true ) retry rescue Zenrows::Error => e puts "ZenRows error: #{e.message}" end ``` ``` -------------------------------- ### Zenrows Screenshot Request Source: https://github.com/swistaczek/zenrows-rb/blob/main/README.md Code snippet for making a Zenrows request to capture screenshots, with options for full-page screenshots and JSON responses. ```ruby http = client.http( js_render: true, screenshot: true, # Take screenshot screenshot_fullpage: true, # Full page json_response: true # Get JSON with screenshot data ) ``` -------------------------------- ### Zenrows HTTP Client Options (Ruby) Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Defines the various configuration options available for the `zenrows_http_client` method. These options control aspects like connection timeouts, JavaScript rendering behavior, proxy settings, browser dimensions, and headers. It also lists helper methods for SSL context, proxy URL generation, and DNS resolution. ```ruby zenrows_http_client(opts = {}) do # Connection :connect_timeout # default 5s :read_timeout # default 180s (auto-calc with js_render) # JavaScript Rendering :js_render # boolean - headless browser :wait # int/duration - wait time (ms or ActiveSupport::Duration) :js_instructions # JSON array - browser automation :json_response # boolean - get JSON instead of HTML :screenshot # boolean - take screenshot :screenshot_fullpage # boolean :screenshot_selector # CSS selector # Proxy :premium_proxy # boolean - residential IPs :proxy_country # string - country code (enables premium) :session_id # bool/string - session persistence # Browser :window_height # int :window_width # int # Headers :headers # Hash :custom_headers # boolean - enable custom headers :original_status # boolean - return original HTTP status end # Helper methods zenrows_ssl_context # SSL context (verify_mode: NONE) http_zenrows_proxy_url(opts) # Build proxy URL http_zenrows_proxy_array(opts) # [host, port, user, pass] wss_zenrows_proxy_url(opts) # WebSocket proxy URL ensure_dns_resolved(url, opts) # DNS pre-resolution with caching ``` -------------------------------- ### Capture Screenshot of Specific Element Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This code captures a screenshot of a specific HTML element identified by a CSS selector. It uses the `screenshot` and `screenshot_selector` parameters. ```ruby require 'zenrows' api = Zenrows::ApiClient.new url = "YOUR_URL_HERE" response = api.get( url, screenshot: true, screenshot_selector: '.product-gallery', json_response: true ) # The screenshot can be accessed via response.screenshot ``` -------------------------------- ### ZenRows Gem Directory Structure (Conceptual) Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Illustrates the proposed directory structure for the `zenrows-rb` gem. This structure organizes core gem logic, configuration, client components, request/response handling, error management, proxy utilities, JS instruction DSL, and adapters for different HTTP backends like http.rb, Faraday, and Net::HTTP. It also includes directories for type signatures (RBS), tests (RSpec), and documentation files. ```directory zenrows-rb/ ├── lib/ │ ├── zenrows.rb # Main entry, configuration │ ├── zenrows/ │ │ ├── version.rb │ │ ├── configuration.rb # Global config (api_key, defaults) │ │ ├── client.rb # Main client class │ │ ├── request.rb # Request builder │ │ ├── response.rb # Response wrapper │ │ ├── errors.rb # Custom exceptions │ │ ├── proxy.rb # Proxy URL builder │ │ ├── js_instructions.rb # JS instruction builder (DSL) │ │ └── backends/ │ │ ├── base.rb # Backend interface │ │ ├── http_rb.rb # http.rb adapter (primary) │ │ ├── faraday.rb # Faraday adapter (future) │ │ └── net_http.rb # Net::HTTP adapter (future) ├── sig/ # RBS type signatures ├── spec/ # RSpec tests ├── .yardopts ├── zenrows.gemspec ├── Gemfile ├── README.md ├── CHANGELOG.md └── LICENSE ``` -------------------------------- ### Manage Sessions for Consistent IP Addresses Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This section illustrates how to maintain consistent IP addresses across multiple requests using ZenRows session management. It covers auto-generated and custom session IDs, along with session duration settings. ```ruby require 'zenrows' client = Zenrows::Client.new # Auto-generated session ID http = client.http( premium_proxy: true, session_id: true, # Random session ID session_ttl: '30m' # Session lasts 30 minutes ) # Multiple requests use same IP response1 = http.get('https://site.com/page1', ssl_context: client.ssl_context) response2 = http.get('https://site.com/page2', ssl_context: client.ssl_context) # Custom session ID user_id = "some_user_id" session_id = "user_#{user_id}_#{Time.now.to_i}" http = client.http( premium_proxy: true, session_id: session_id, session_ttl: '1h' ) # Session TTL options: '30s', '5m', '30m', '1h', '1d' http = client.http( premium_proxy: true, session_id: true, session_ttl: '1d' # Session lasts 1 day ) # Different proxy countries per session http_us = client.http( premium_proxy: true, proxy_country: 'us', session_id: 'us_session', session_ttl: '30m' ) http_gb = client.http( premium_proxy: true, proxy_country: 'gb', session_id: 'gb_session', session_ttl: '30m' ) ``` -------------------------------- ### Define CSS Selectors for Data Extraction with Zenrows::CssExtractor Source: https://context7.com/swistaczek/zenrows-rb/llms.txt Zenrows::CssExtractor provides a DSL for defining CSS selectors to extract structured data from web pages. It allows you to specify which elements to extract, their corresponding CSS selectors, and optionally attributes to retrieve (like 'href' or 'src'). This can be used directly with Zenrows::ApiClient. The 'zenrows' gem is required. ```ruby require 'zenrows' # Build extractor with DSL extractor = Zenrows::CssExtractor.build do extract :title, 'h1.product-title' extract :price, '.price-value' extract :description, 'div.description' # Extract attributes extract :link, 'a.product-link', attribute: 'href' extract :image, 'img.main-image', attribute: 'src' # Convenience methods links :product_links, 'a.product' images :gallery, '.gallery img' end # Use with ApiClient api = Zenrows::ApiClient.new response = api.get( 'https://example.com/product/123', css_extractor: extractor ) puts response.extracted # => { # "title" => "Product Name", # "price" => "$49.99", # "description" => "Product description...", # "link" => "https://example.com/…", # "image" => "https://cdn.example.com/img.jpg", # "product_links" => ["url1", "url2", "url3"], # "gallery" => ["img1.jpg", "img2.jpg", "img3.jpg"] # } # Alternative: use hash directly response = api.get( url, css_extractor: { title: 'h1', links: 'a @href', prices: '.price' } ) # E-commerce product scraping extractor = Zenrows::CssExtractor.build do extract :name, 'h1[data-testid="product-title"]' extract :price, '[data-testid="price"]' extract :rating, '.rating-value' extract :reviews, '.review-count' extract :availability, '.stock-status' images :product_images, '.product-gallery img' links :related_products, '.related-product a' end puts extractor.size # => 7 puts extractor.empty? # => false puts extractor.to_h # => {:name => "h1[...", ...} ``` -------------------------------- ### Proxy-based Scraping with Zenrows::Client Source: https://context7.com/swistaczek/zenrows-rb/llms.txt Utilizes the Zenrows::Client to route HTTP requests through the ZenRows proxy. Supports JavaScript rendering, premium proxies, geolocation, wait conditions, session persistence, and resource blocking. The client returns standard HTTP client instances configured with ZenRows proxy settings. ```ruby require 'zenrows' # Configure API key Zenrows.configure do |config| config.api_key = 'YOUR_API_KEY' end # Create client client = Zenrows::Client.new # Basic request with JavaScript rendering http = client.http(js_render: true, premium_proxy: true) response = http.get('https://example.com', ssl_context: client.ssl_context) puts response.status.code # => 200 puts response.body.to_s # => "..." # Request with geolocation http = client.http( js_render: true, premium_proxy: true, proxy_country: 'us' ) response = http.get('https://amazon.com', ssl_context: client.ssl_context) # Request with wait conditions http = client.http( js_render: true, wait: 5000, # Wait 5 seconds after page load wait_for: '.products' # Wait for selector to appear ) response = http.get(url, ssl_context: client.ssl_context) # Session persistence for consistent IP http = client.http( premium_proxy: true, session_id: true, # Auto-generate session session_ttl: '30m' # Session duration ) response1 = http.get(url1, ssl_context: client.ssl_context) response2 = http.get(url2, ssl_context: client.ssl_context) # Same IP # Block resources for faster loading http = client.http( js_render: true, block_resources: 'image,media,font' ) response = http.get(url, ssl_context: client.ssl_context) ``` -------------------------------- ### Retrieve Response Headers and Metadata Source: https://context7.com/swistaczek/zenrows-rb/llms.txt This snippet shows how to access various metadata from the ZenRows API response, including HTTP headers, concurrency limits, request cost, and the final URL after any redirects. ```ruby response = api.get( url, screenshot: true, screenshot_fullpage: true, json_response: true ) puts response.headers # => {"Content-Type" => "...", ...} puts response.concurrency_limit # => 100 puts response.concurrency_remaining # => 95 puts response.request_cost # => 1.0 puts response.final_url # => Final URL after redirects ``` -------------------------------- ### Zenrows Ruby Gem Dependencies Source: https://github.com/swistaczek/zenrows-rb/blob/main/plan.md Defines the primary and development dependencies for the Zenrows Ruby gem. It specifies the required versions for the 'http' and 'addressable' gems for core functionality, and 'rspec', 'vcr', 'webmock', 'yard', and 'rubocop' for development and testing. ```ruby # zenrows.gemspec spec.add_dependency 'http', '~> 5.0' # Primary HTTP backend spec.add_dependency 'addressable', '~> 2.8' # URL handling spec.add_development_dependency 'rspec', '~> 3.12' spec.add_development_dependency 'vcr', '~> 6.0' spec.add_development_dependency 'webmock', '~> 3.0' spec.add_development_dependency 'yard', '~> 0.9' spec.add_development_dependency 'rubocop', '~> 1.0' ```