# Extract data

> Pick values out of a response with CSS, XPath or JSON paths: text, attributes, numbers, regular expressions and nested lists – with or without a browser.

Source: https://docs.virginproxy.com/extract/

Instead of parsing the HTML yourself, name the values you want with CSS selectors, XPath or JSON paths. They come back in `extracted` – typed, cleaned up and nested the way you need them – next to the full page.

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://quotes.toscrape.com/",
    "extract": {
      "first_quote": ".quote .text",
      "authors": {
        "selector": ".quote .author",
        "all": true
      },
      "tags": {
        "selector": ".tag-item a",
        "all": true
      },
      "next_page": {
        "selector": ".next a",
        "attr": "href"
      }
    }
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://quotes.toscrape.com/",
        "extract": {
            "first_quote": ".quote .text",
            "authors": {"selector": ".quote .author", "all": True},
            "tags": {"selector": ".tag-item a", "all": True},
            "next_page": {"selector": ".next a", "attr": "href"},
        },
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["extracted"]["first_quote"])
print(data["extracted"]["authors"][:3], data["extracted"]["next_page"])
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://quotes.toscrape.com/",
    extract: {
      first_quote: ".quote .text",
      authors: { selector: ".quote .author", all: true },
      tags: { selector: ".tag-item a", all: true },
      next_page: { selector: ".next a", attr: "href" },
    },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
console.log(data.extracted.first_quote);
console.log(data.extracted.authors.slice(0, 3), data.extracted.next_page);
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://quotes.toscrape.com/",
    "extract": {
        "first_quote": ".quote .text",
        "authors": {"selector": ".quote .author", "all": True},
        "tags": {"selector": ".tag-item a", "all": True},
        "next_page": {"selector": ".next a", "attr": "href"},
    },
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://quotes.toscrape.com/",
  extract: {
    first_quote: ".quote .text",
    authors: { selector: ".quote .author", all: true },
    tags: { selector: ".tag-item a", all: true },
    next_page: { selector: ".next a", attr: "href" },
  },
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://quotes.toscrape.com/",
        "extract" => [
            "first_quote" => ".quote .text",
            "authors" => ["selector" => ".quote .author", "all" => true],
            "tags" => ["selector" => ".tag-item a", "all" => true],
            "next_page" => ["selector" => ".next a", "attr" => "href"],
        ],
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo json_encode($data["extracted"]["first_quote"], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
echo json_encode([$data["extracted"]["authors"], $data["extracted"]["next_page"]], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://quotes.toscrape.com/",
  "extract": {
    "first_quote": ".quote .text",
    "authors": {
      "selector": ".quote .author",
      "all": true
    },
    "tags": {
      "selector": ".tag-item a",
      "all": true
    },
    "next_page": {
      "selector": ".next a",
      "attr": "href"
    }
  }
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["extracted"].(map[string]any)["first_quote"])
	fmt.Println(data["extracted"].(map[string]any)["authors"], data["extracted"].(map[string]any)["next_page"])
}
```

POST`/v1/requests`[≈ 1 credit](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL3F1b3Rlcy50b3NjcmFwZS5jb20vIiwiZXh0cmFjdCI6eyJmaXJzdF9xdW90ZSI6Ii5xdW90ZSAudGV4dCIsImF1dGhvcnMiOnsic2VsZWN0b3IiOiIucXVvdGUgLmF1dGhvciIsImFsbCI6dHJ1ZX0sInRhZ3MiOnsic2VsZWN0b3IiOiIudGFnLWl0ZW0gYSIsImFsbCI6dHJ1ZX0sIm5leHRfcGFnZSI6eyJzZWxlY3RvciI6Ii5uZXh0IGEiLCJhdHRyIjoiaHJlZiJ9fX0)

## How to describe a field

`extract` is an object of up to 50 fields. The name (letters, digits, `_ . -`, up to 64) is yours; the value is either a CSS selector or an object:

| Key | Meaning |
| --- | --- |
| `selector` | A CSS selector, up to 500 characters. |
| `xpath` | An XPath expression instead, up to 500 characters. See [XPath](#xpath). |
| `json` | A path into a JSON answer instead, such as `data.items[*].name`. See [JSON answers](#json). |
| `attr` | `text` (default): the visible text, with whitespace tidied up. `html`: the inner HTML. `outer_html`: the element itself. Any other name reads that attribute, for example `href`, `src`, `content`, `data-id`. `href`, `src`, `action` and `data-src` are turned into absolute addresses. |
| `all` | `true`: a list of all matches (up to 1,000) instead of the first one. |
| `type` | `string` (default), `number`, `integer` or `boolean`. See [Types](#types). |
| `regex` | A regular expression applied to the value. See [Regex and default](#regex). |
| `default` | What to return when nothing matched, instead of `null`. Any JSON value. |
| `fields` | Sub-fields read inside each match. See [Nested fields](#nested). |

Each field has exactly one of `selector`, `xpath` and `json`.

## The result

- The first match as a string (or the `type` you asked for), or a list with `"all": true`.
- When nothing matched: `default` if you set one, otherwise `null` (an empty list with `all`). The same when an attribute is missing.
- CSS and XPath fields read HTML; they are `null` when the answer is not HTML. JSON paths read JSON answers.
- With `render` the values are read from the finished page, after scripts and steps. A different [format](https://docs.virginproxy.com/formats/) does not matter: extraction always reads the original answer.

## Types

Prices, ratings and counts arrive as text like `1.299,00 €`. `type` turns them into real values:

| Type | Result | Examples |
| --- | --- | --- |
| `number` | A number. Currency signs, spaces and units are ignored. The last separator followed by one or two digits is the decimal point, so both European and English notation work. | `1.299,00 €` → `1299`, `1,299.00` → `1299`, `12,5 %` → `12.5` |
| `integer` | Like `number`, rounded down. | `4,7 stars` → `4` |
| `boolean` | `true` for any non-empty value except `false`, `0`, `no` and `nein`. | `In stock` → `true` |
| `string` | The text as it is (default). |  |

A value that cannot be read as the type becomes `default` or `null`.

## Regex and default

`regex` picks a part of the value: the first group if the expression has one, otherwise the whole match. No match gives `default` or `null`. The expressions use the RE2 syntax: no look-arounds and no back-references, but guaranteed fast. `regex` runs before `type`.

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://shop.example/product/42",
    "extract": {
      "sku": {
        "selector": ".product-meta",
        "regex": "SKU: ([A-Z0-9-]+)"
      },
      "rating": {
        "selector": ".rating",
        "attr": "aria-label",
        "regex": "([\\d.,]+) out of 5",
        "type": "number"
      },
      "stock": {
        "selector": ".stock-count",
        "type": "integer",
        "default": 0
      }
    }
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://shop.example/product/42",
        "extract": {
            "sku": {"selector": ".product-meta", "regex": "SKU: ([A-Z0-9-]+)"},
            "rating": {
                "selector": ".rating",
                "attr": "aria-label",
                "regex": "([\\d.,]+) out of 5",
                "type": "number",
            },
            "stock": {"selector": ".stock-count", "type": "integer", "default": 0},
        },
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["extracted"])
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://shop.example/product/42",
    extract: {
      sku: { selector: ".product-meta", regex: "SKU: ([A-Z0-9-]+)" },
      rating: {
        selector: ".rating",
        attr: "aria-label",
        regex: "([\\d.,]+) out of 5",
        type: "number",
      },
      stock: { selector: ".stock-count", type: "integer", default: 0 },
    },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
console.log(data.extracted);
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://shop.example/product/42",
    "extract": {
        "sku": {"selector": ".product-meta", "regex": "SKU: ([A-Z0-9-]+)"},
        "rating": {
            "selector": ".rating",
            "attr": "aria-label",
            "regex": "([\\d.,]+) out of 5",
            "type": "number",
        },
        "stock": {"selector": ".stock-count", "type": "integer", "default": 0},
    },
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://shop.example/product/42",
  extract: {
    sku: { selector: ".product-meta", regex: "SKU: ([A-Z0-9-]+)" },
    rating: {
      selector: ".rating",
      attr: "aria-label",
      regex: "([\\d.,]+) out of 5",
      type: "number",
    },
    stock: { selector: ".stock-count", type: "integer", default: 0 },
  },
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://shop.example/product/42",
        "extract" => [
            "sku" => ["selector" => ".product-meta", "regex" => "SKU: ([A-Z0-9-]+)"],
            "rating" => [
                "selector" => ".rating",
                "attr" => "aria-label",
                "regex" => "([\\d.,]+) out of 5",
                "type" => "number",
            ],
            "stock" => [
                "selector" => ".stock-count",
                "type" => "integer",
                "default" => 0,
            ],
        ],
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo json_encode($data["extracted"], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://shop.example/product/42",
  "extract": {
    "sku": {
      "selector": ".product-meta",
      "regex": "SKU: ([A-Z0-9-]+)"
    },
    "rating": {
      "selector": ".rating",
      "attr": "aria-label",
      "regex": "([\\d.,]+) out of 5",
      "type": "number"
    },
    "stock": {
      "selector": ".stock-count",
      "type": "integer",
      "default": 0
    }
  }
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["extracted"])
}
```

POST`/v1/requests`[≈ 1 credit](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL3Nob3AuZXhhbXBsZS9wcm9kdWN0LzQyIiwiZXh0cmFjdCI6eyJza3UiOnsic2VsZWN0b3IiOiIucHJvZHVjdC1tZXRhIiwicmVnZXgiOiJTS1U6IChbQS1aMC05LV0rKSJ9LCJyYXRpbmciOnsic2VsZWN0b3IiOiIucmF0aW5nIiwiYXR0ciI6ImFyaWEtbGFiZWwiLCJyZWdleCI6IihbXFxkLixdKykgb3V0IG9mIDUiLCJ0eXBlIjoibnVtYmVyIn0sInN0b2NrIjp7InNlbGVjdG9yIjoiLnN0b2NrLWNvdW50IiwidHlwZSI6ImludGVnZXIiLCJkZWZhdWx0IjowfX19)

*Result:*

```json
"extracted": {
  "sku": "TR-2-42",
  "rating": 4.6,
  "stock": 0
}
```

## Nested fields

Lists of things – products, search results, reviews – are easiest with `fields`: the outer selector finds each item, the sub-fields are read inside it. With `all` you get a list of objects, without it one object. Sub-fields can have their own `fields`, up to 3 levels deep. With `fields`, the outer field's `attr`, `type` and `regex` do not apply.

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://quotes.toscrape.com/",
    "extract": {
      "quotes": {
        "selector": ".quote",
        "all": true,
        "fields": {
          "text": ".text",
          "author": ".author",
          "author_url": {
            "selector": "a[href^=\"/author/\"]",
            "attr": "href"
          },
          "tags": {
            "selector": ".tag",
            "all": true
          }
        }
      }
    }
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://quotes.toscrape.com/",
        "extract": {
            "quotes": {
                "selector": ".quote",
                "all": True,
                "fields": {
                    "text": ".text",
                    "author": ".author",
                    "author_url": {"selector": "a[href^=\"/author/\"]", "attr": "href"},
                    "tags": {"selector": ".tag", "all": True},
                },
            },
        },
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["extracted"]["quotes"][0])
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://quotes.toscrape.com/",
    extract: {
      quotes: {
        selector: ".quote",
        all: true,
        fields: {
          text: ".text",
          author: ".author",
          author_url: { selector: "a[href^=\"/author/\"]", attr: "href" },
          tags: { selector: ".tag", all: true },
        },
      },
    },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
console.log(data.extracted.quotes[0]);
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://quotes.toscrape.com/",
    "extract": {
        "quotes": {
            "selector": ".quote",
            "all": True,
            "fields": {
                "text": ".text",
                "author": ".author",
                "author_url": {"selector": "a[href^=\"/author/\"]", "attr": "href"},
                "tags": {"selector": ".tag", "all": True},
            },
        },
    },
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://quotes.toscrape.com/",
  extract: {
    quotes: {
      selector: ".quote",
      all: true,
      fields: {
        text: ".text",
        author: ".author",
        author_url: { selector: "a[href^=\"/author/\"]", attr: "href" },
        tags: { selector: ".tag", all: true },
      },
    },
  },
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://quotes.toscrape.com/",
        "extract" => [
            "quotes" => [
                "selector" => ".quote",
                "all" => true,
                "fields" => [
                    "text" => ".text",
                    "author" => ".author",
                    "author_url" => ["selector" => "a[href^=\"/author/\"]", "attr" => "href"],
                    "tags" => ["selector" => ".tag", "all" => true],
                ],
            ],
        ],
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo json_encode($data["extracted"]["quotes"][0], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://quotes.toscrape.com/",
  "extract": {
    "quotes": {
      "selector": ".quote",
      "all": true,
      "fields": {
        "text": ".text",
        "author": ".author",
        "author_url": {
          "selector": "a[href^=\"/author/\"]",
          "attr": "href"
        },
        "tags": {
          "selector": ".tag",
          "all": true
        }
      }
    }
  }
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["extracted"].(map[string]any)["quotes"].([]any)[0])
}
```

POST`/v1/requests`[≈ 1 credit](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL3F1b3Rlcy50b3NjcmFwZS5jb20vIiwiZXh0cmFjdCI6eyJxdW90ZXMiOnsic2VsZWN0b3IiOiIucXVvdGUiLCJhbGwiOnRydWUsImZpZWxkcyI6eyJ0ZXh0IjoiLnRleHQiLCJhdXRob3IiOiIuYXV0aG9yIiwiYXV0aG9yX3VybCI6eyJzZWxlY3RvciI6ImFbaHJlZl49XCIvYXV0aG9yL1wiXSIsImF0dHIiOiJocmVmIn0sInRhZ3MiOnsic2VsZWN0b3IiOiIudGFnIiwiYWxsIjp0cnVlfX19fX0)

*Result:*

```json
"extracted": {
  "quotes": [
    {
      "text": "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”",
      "author": "Albert Einstein",
      "author_url": "https://quotes.toscrape.com/author/Albert-Einstein",
      "tags": ["change", "deep-thoughts", "thinking", "world"]
    },
    …
  ]
}
```

## XPath

Some things are hard to say in CSS: an element by its text, or the cell next to a label. `xpath` takes an XPath 1.0 expression. `attr` works as with CSS; an expression that selects an attribute or text directly returns its value.

*Request body (part):*

```json
{
  "extract": {
    "weight": {
      "xpath": "//th[normalize-space()='Weight']/following-sibling::td"
    },
    "brand_link": {
      "xpath": "//a[contains(@class, 'brand')]/@href"
    }
  }
}
```

## JSON answers

When the target answers with JSON – an API, or a request captured from a web app – `json` picks values by path: names separated by dots, `[n]` for one list entry and `[*]` for all of them, which returns a list.

*Request body:*

```json
{
  "url": "https://shop.example/api/products?page=1",
  "extract": {
    "names": {
      "json": "data.items[*].name"
    },
    "first_price": {
      "json": "data.items[0].price",
      "type": "number"
    },
    "total": {
      "json": "meta.total",
      "type": "integer"
    }
  }
}
```

*Result:*

```json
"extracted": {
  "names": ["Trail Runner 2", "Road Runner", "Hiking Boot X"],
  "first_price": 129,
  "total": 48
}
```

## Limits and errors

- At most 50 fields at the top level and 200 in total, sub-fields included.
- Selectors, XPath expressions, JSON paths and regular expressions up to 500 characters each.
- Nested `fields` up to 3 levels deep.
- A field that breaks a rule is answered at once with `invalid_extract` (400). The message names the field path, for example `extract.quotes.fields.tags`.

Extraction costs nothing extra. If you only need the values, you still pay for the page's size: `bytes.down` counts what the target sent.

> **Tip:** For the usual suspects – links, images, metadata, tables, JSON-LD – you do not need selectors at all: use [parse](https://docs.virginproxy.com/parse/).
