Get an API key Your API keys

Extract data

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 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"
      }
    }
  }'
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"])
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);
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)
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
$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;
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"])
}
require "json"
require "net/http"

uri = URI("https://api.virginproxy.com/v1/requests")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer " + ENV.fetch("VP_KEY")
req["Content-Type"] = "application/json"
req.body = JSON.generate({
  "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" },
  },
})

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 180) { |http| http.request(req) }
data = JSON.parse(res.body)
abort(data["error"]["code"] + ": " + data["error"]["message"]) unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(data)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class Main {
    public static void main(String[] args) throws Exception {
        String payload = """
            {
              "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"
                }
              }
            }
            """;
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.virginproxy.com/v1/requests"))
            .header("Authorization", "Bearer " + System.getenv("VP_KEY"))
            .header("Content-Type", "application/json")
            .timeout(Duration.ofSeconds(180))
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();
        HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() >= 300) {
            System.err.println(res.statusCode() + " " + res.body()); // the error object: code, message
            System.exit(1);
        }
        System.out.println(res.body()); // JSON: read it with the JSON library of your choice
    }
}
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(180) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VP_KEY"));
var payload = """
    {
      "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"
        }
      }
    }
    """;
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.virginproxy.com/v1/requests");
req.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var res = await http.SendAsync(req);
using var data = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
if (!res.IsSuccessStatusCode)
{
    var e = data.RootElement.GetProperty("error");
    Console.Error.WriteLine(e.GetProperty("code") + ": " + e.GetProperty("message"));
    Environment.Exit(1);
}
Console.WriteLine(data.RootElement);

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:

KeyMeaning
selectorA CSS selector, up to 500 characters.
xpathAn XPath expression instead, up to 500 characters. See XPath.
jsonA path into a JSON answer instead, such as data.items[*].name. See JSON answers.
attrtext (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.
alltrue: a list of all matches (up to 1,000) instead of the first one.
typestring (default), number, integer or boolean. See Types.
regexA regular expression applied to the value. See Regex and default.
defaultWhat to return when nothing matched, instead of null. Any JSON value.
fieldsSub-fields read inside each match. See Nested fields.

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

The result

Types

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

TypeResultExamples
numberA 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
integerLike number, rounded down.4,7 stars → 4
booleantrue for any non-empty value except false, 0, no and nein.In stock → true
stringThe 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 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
      }
    }
  }'
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"])
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);
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)
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
$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;
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"])
}
require "json"
require "net/http"

uri = URI("https://api.virginproxy.com/v1/requests")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer " + ENV.fetch("VP_KEY")
req["Content-Type"] = "application/json"
req.body = JSON.generate({
  "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,
    },
  },
})

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 180) { |http| http.request(req) }
data = JSON.parse(res.body)
abort(data["error"]["code"] + ": " + data["error"]["message"]) unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(data["extracted"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class Main {
    public static void main(String[] args) throws Exception {
        String payload = """
            {
              "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
                }
              }
            }
            """;
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.virginproxy.com/v1/requests"))
            .header("Authorization", "Bearer " + System.getenv("VP_KEY"))
            .header("Content-Type", "application/json")
            .timeout(Duration.ofSeconds(180))
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();
        HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() >= 300) {
            System.err.println(res.statusCode() + " " + res.body()); // the error object: code, message
            System.exit(1);
        }
        System.out.println(res.body()); // JSON: read it with the JSON library of your choice
    }
}
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(180) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VP_KEY"));
var payload = """
    {
      "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
        }
      }
    }
    """;
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.virginproxy.com/v1/requests");
req.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var res = await http.SendAsync(req);
using var data = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
if (!res.IsSuccessStatusCode)
{
    var e = data.RootElement.GetProperty("error");
    Console.Error.WriteLine(e.GetProperty("code") + ": " + e.GetProperty("message"));
    Environment.Exit(1);
}
Console.WriteLine(data.RootElement.GetProperty("extracted"));
Result
"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 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
          }
        }
      }
    }
  }'
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])
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]);
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)
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
$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;
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])
}
require "json"
require "net/http"

uri = URI("https://api.virginproxy.com/v1/requests")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer " + ENV.fetch("VP_KEY")
req["Content-Type"] = "application/json"
req.body = JSON.generate({
  "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 },
      },
    },
  },
})

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 180) { |http| http.request(req) }
data = JSON.parse(res.body)
abort(data["error"]["code"] + ": " + data["error"]["message"]) unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(data["extracted"]["quotes"][0])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class Main {
    public static void main(String[] args) throws Exception {
        String payload = """
            {
              "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
                    }
                  }
                }
              }
            }
            """;
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.virginproxy.com/v1/requests"))
            .header("Authorization", "Bearer " + System.getenv("VP_KEY"))
            .header("Content-Type", "application/json")
            .timeout(Duration.ofSeconds(180))
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();
        HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() >= 300) {
            System.err.println(res.statusCode() + " " + res.body()); // the error object: code, message
            System.exit(1);
        }
        System.out.println(res.body()); // JSON: read it with the JSON library of your choice
    }
}
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(180) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VP_KEY"));
var payload = """
    {
      "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
            }
          }
        }
      }
    }
    """;
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.virginproxy.com/v1/requests");
req.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var res = await http.SendAsync(req);
using var data = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
if (!res.IsSuccessStatusCode)
{
    var e = data.RootElement.GetProperty("error");
    Console.Error.WriteLine(e.GetProperty("code") + ": " + e.GetProperty("message"));
    Environment.Exit(1);
}
Console.WriteLine(data.RootElement.GetProperty("extracted").GetProperty("quotes")[0]);
Result
"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)
{
  "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
{
  "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
"extracted": {
  "names": ["Trail Runner 2", "Road Runner", "Hiking Boot X"],
  "first_price": 129,
  "total": 48
}

Limits and errors

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.

Was this page helpful?

Last updated