# Ordered Gallery Image Export (`sapph1re/ordered-gallery-image-export`) Actor

Export ordered image occurrences from a selected HTML gallery. Keep repeated images, picture/srcset variants and raw source evidence grouped by occurrence. Label lazy-load attributes as hints and report partial results. No JavaScript or image downloads.

- **URL**: https://apify.com/sapph1re/ordered-gallery-image-export.md
- **Developed by:** [Roman V](https://apify.com/sapph1re) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$1.00 / 1,000 delivered image occurrences

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Ordered Gallery Image Export

Export the image occurrences declared inside one gallery container on each page. Each dataset row keeps its HTML position, fallback URL, ordered picture/source declarations, responsive candidates and raw opening tags. Repeated URLs stay at their separate positions. JSON export preserves the nested groups; CSV may encode nested values as JSON text.

### Input

Provide `pages`, an array of one to ten objects with `url` and `selector`. Each selector must match exactly one container. Supported CSS includes tag, ID, class, attribute equality, descendants and children, at most 200 characters/eight whitespace-separated components. Selector lists and pseudo selectors are refused. `maxOccurrences` defaults to 20 and must be between 1 and 1,000. Omitted input and `{}` use Python.org's `.site-headline` as a small, useful example and persist the effective input. Replace the example with pages you are authorized to inspect.

```json
{"pages":[{"url":"https://www.python.org/","selector":".site-headline"}],"maxOccurrences":20}
```

### Output and ordering

`position` is one-based inside the selected gallery. `pageIndex` is zero-based input order. `occurrenceId` is deterministic from requested page, input position, selector and occurrence position. Repeating a URL on another page or input position does not merge records. IDs are positional identifiers, not permanent image identities.

`image` holds the img's declarations. `sources` holds direct preceding source siblings when the img is directly inside picture, in source order. Each declaration includes `rawStartTag`, ordered `rawAttributes` (entity-decoded values, including duplicates), first-value `attributes`, `candidates`, separately labeled `hints`, and `issues`. Candidates retain raw URL, resolved URL, original descriptor, attribute, media and type. `alt: null` means absent; `alt: ""` means explicitly empty. Missing or invalid fallback has `fallbackUrl: null`.

Source order is the parser's HTML order, not visual CSS order. This HTTP-only tool does not execute JavaScript, pick currentSrc, inspect CSS backgrounds, test image URLs, download image binaries, infer original resolution or claim that responsive alternatives are identical images. It excludes inert template/noscript descendants. Malformed HTML follows Python's HTML parser, not a browser's HTML5 tree repair. Raw opening tags preserve the evidence for inspection. Invalid or unsupported descriptors and URL schemes are labeled; they do not invalidate adjacent candidates. Width/density candidates are preserved, without browser selection. Attribute-level mixed or duplicate descriptors appear in issues. Nonstandard data-src/data-srcset are hints and never override src.

The first base href resolves relative declarations. Invalid base values are reported. Image references may be relative, extensionless, contain commas or Unicode. Only declared HTTP(S) references are resolved; their hosts are never contacted. Page-fetch URLs themselves must be ASCII HTTP(S), standard port 80/443, without credentials, fragments or secret-looking query fields. No authentication, proxies, custom headers, crawling or cross-site API calls are offered. Redirects are checked independently; HTTPS cannot downgrade to HTTP.

Use only pages and image declarations you are authorized to inspect and reuse. Check the site's terms and robots policy before submitting a page. This bounded exact-URL tool does not fetch robots.txt or interpret its rules and does not treat public reachability as permission. No access-control bypass is attempted.

The default dataset contains only selected image occurrence rows. `OUTPUT` in the default key-value store contains page outcomes, counters and the delivery receipt, without an image inventory. USEFUL means complete useful extraction; EMPTY means no img in the selected HTML; PARTIAL means a page or cap prevented complete extraction. Missing/ambiguous selectors are explicit UNOBSERVED page outcomes. FAILED/INVALID run outcomes exit nonzero. An empty or unobserved selector does not prove that a site has no dynamic images. Healthy page rows survive other page failures. An occurrence exceeding a bound is refused whole and its position appears in diagnostics.

### Limits and resource use

Limits: ten exact pages, concurrency one, three redirects per page, forty HTTP request attempts and forty page sockets; one checked DNS destination/socket per request after validating all up to sixteen DNS answers. There are no connection or append retries. Responses allow 2 MiB encoded body and 2 MiB decoded body, 12 MiB each per collection; 50,000 opening tags and 128 explicit nesting levels; 100 occurrences/page; 1,000/run; twenty candidates including hints/occurrence; 5,000 candidates/run; 16 KiB serialized/row; 3 MiB for the single serialized SDK append. Serialization limits include indentation, escaping, commas and brackets.

Each HTTP request has fifteen seconds, collection ninety seconds and runtime work after SDK startup 120 seconds. Protocol input is separately bounded at 2 MiB plus 64 KiB per response and 12 MiB plus forty 64 KiB header allowances per collection. Counters distinguish protocol bytes observed from encoded body bytes read and decoded bytes produced. Detection may observe one body/decompression sentinel byte above a bound or one protocol callback above a bound; these are counted and rejected, not hidden or described as exact network billing. TLS/OS buffering and packet overhead are not measured. Encoded and decoded bytes from failed responses are counted when consumed. No further request starts after an aggregate limit.

The default and minimum memory are 256 MiB. Dependencies are pinned with hashes.

### Pricing and event caps

With pay-per-event pricing enabled at $0.001 per confirmed delivered occurrence, variants are included in that occurrence's price. At this rate, the default twenty-occurrence limit has an event ceiling of $0.02, and the maximum 1,000 has an event ceiling of $1. Check the current pricing shown in Apify Console before starting a run. Free/unpriced validation records zero charged events; inconsistent declared pay-per-event context fails before fetching.

A supported positive `maxTotalChargeUsd` reduces selection to the number of whole occurrence events it can fund. For example, $0.0015 allows one occurrence at a $0.001 event price, not one and a half occurrences. The hosted API may ignore a literal zero or reject a cap below one event. Do not use `maxTotalChargeUsd=0` as a no-spend guarantee.

These are event ceilings, not total infrastructure-cost estimates. Compute, data transfer, storage and API operations still incur platform costs under the billing terms shown in Console; an event cap does not bound all of those costs. Confirmed empty output has no occurrence events. If delivery or charging is ambiguous, inspect the recorded delivery status instead of assuming that the counts or costs are zero.

### Delivery and recovery

Delivery uses one SDK append below its pinned chunk threshold. A persisted intent prevents replay after ambiguous delivery. The dataset API acknowledgement is recorded separately from the SDK charge receipt. If a later SDK or receipt error occurs, DELIVERED_CHARGE_UNKNOWN preserves confirmed delivered and per-page counts while chargedOccurrences stays null. Ambiguous transport remains UNKNOWN for both counts. A separate digest-verified DELIVERY_RECEIPT stores only diagnostics and counts, so a journal or OUTPUT failure can preserve facts for restart. A completed restart returns its verified saved receipt without another source request or append. An incomplete or malformed restart fails closed and requires operator reconciliation. Known zero requires a complete digest-verified pre-append snapshot with appendAttempted false; an incomplete or corrupt snapshot never proves zero. A separately verified delivery receipt can preserve delivered counts when the journal is unusable. If all durable writes fail or the process stops before saving an acknowledgement, restart reports unknown; it cannot reconstruct unavailable facts. No automatic retry or manual charge call exists.

# Actor input Schema

## `pages` (type: `array`):

One to ten URL/selector objects. HTTP(S), standard ports, public network only. CSS subset: tag, id, class, attribute equality, descendant or child. No-body and {} use the Python logo demonstration.

## `maxOccurrences` (type: `integer`):

Total occurrence cap across pages. A lower event budget can reduce it. Variants are included in one occurrence.

## Actor input object example

```json
{
  "pages": [
    {
      "url": "https://www.python.org/",
      "selector": ".site-headline"
    }
  ],
  "maxOccurrences": 20
}
```

# Actor output Schema

## `occurrences` (type: `string`):

No description

## `outcomes` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "pages": [
        {
            "url": "https://www.python.org/",
            "selector": ".site-headline"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("sapph1re/ordered-gallery-image-export").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "pages": [{
            "url": "https://www.python.org/",
            "selector": ".site-headline",
        }] }

# Run the Actor and wait for it to finish
run = client.actor("sapph1re/ordered-gallery-image-export").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "pages": [
    {
      "url": "https://www.python.org/",
      "selector": ".site-headline"
    }
  ]
}' |
apify call sapph1re/ordered-gallery-image-export --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,sapph1re/ordered-gallery-image-export"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/mZ7CGqaQxPhfmuSP1/builds/EMZxDo8hvyHfPNhZ3/openapi.json
