Get an API key Your API keys

Pages with JavaScript

Some pages are empty until their scripts have run: search results, shops built as web apps, dashboards and single-page apps. render loads the page in a real browser, lets its scripts run and returns the finished page as HTML – plus screenshots, a PDF, the page's own background requests and the results of your steps if you ask for them.

Render a page

This demo page builds its quotes with JavaScript. A plain request gets an empty frame; rendered, the quotes are there.

curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://quotes.toscrape.com/js/",
    "render": {
      "wait_for": ".quote"
    }
  }'
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/js/",
        "render": {"wait_for": ".quote"},
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["rendered"], data["status"], data["body"].count('class="quote"'), data["cost"]["credits"])
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/js/",
    render: { wait_for: ".quote" },
  }),
  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.rendered, data.status, data.body.split('class="quote"').length - 1, data.cost.credits);
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://quotes.toscrape.com/js/",
    "render": {"wait_for": ".quote"},
})
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/js/",
  render: { wait_for: ".quote" },
});
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/js/",
        "render" => ["wait_for" => ".quote"],
    ], 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["rendered"], $data["status"], $data["cost"]["credits"]], 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/js/",
  "render": {
    "wait_for": ".quote"
  }
}`)
	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["rendered"], data["status"], data["cost"].(map[string]any)["credits"])
}
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/js/",
  "render" => { "wait_for" => ".quote" },
})

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/js/",
              "render": {
                "wait_for": ".quote"
              }
            }
            """;
        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/js/",
      "render": {
        "wait_for": ".quote"
      }
    }
    """;
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);

"render": true is enough for many pages. The object form adds everything below. The device the page sees (time zone, location, screen, colour scheme, device properties, stored values) is described on Device and environment.

What you get back

FieldMeaning
bodyThe page as HTML after its scripts and your steps ran, always UTF-8 text.
status, headers, final_url, redirectsOf the page itself.
cookiesEvery cookie the browser holds at the end.
renderedtrue.
screenshot, screenshot_typeThe screenshot as base64 and its type (image/png, image/jpeg or image/webp) when you asked for one, otherwise null.
pdfThe page as a base64 PDF, only with "pdf": true.
stepsOne entry per action: {"action", "ok", "skipped"?, "error"?, "value"?}. value is the result of an evaluate step.
capturedThe background requests you asked for with capture: {"url", "method", "status", "content_type", "body", "body_encoding", "truncated"}.
extractedWith extract, see Extract data.

Options

FieldTypeMeaning
wait_untilstringWhen the page counts as loaded: load (default, everything loaded), domcontentloaded (the HTML is there, faster) or networkidle (no request ran for half a second, at most 15 seconds – for pages that keep fetching data after loading).
wait_forstringA CSS selector, up to 500 characters. Waits until such an element is visible.
wait_msinteger0 to 15,000. Waits this long at the end, for content that arrives late.
scrollinteger0 to 20. Scrolls to the bottom this many times, with a short pause each time, so that content which loads while you scroll appears.
screenshotboolean or objecttrue: the visible area as PNG. Object: {"full_page": true} for the whole page (up to 16,000 pixels high), {"selector": "#chart"} for one element, "format": "png" | "jpeg" | "webp", "quality": 1–100 for JPEG and WebP.
pdfbooleantrue also returns the page as a PDF (with backgrounds).
blocklistWhat the browser does not load: any of image, media, font, stylesheet. Default ["image", "media", "font"], which saves time and credits. [] loads everything, for example for a screenshot with pictures.
block_urlslistUp to 50 address patterns the browser does not load, for example trackers or ads. Without * a pattern matches anywhere in the address; with * it is a wildcard: *analytics.example*, https://cdn.example/*.js.
capturelistUp to 10 address patterns (same rules). Matching background requests of the page (XHR, fetch, scripts …) come back in captured, at most 20, each body up to 1 MB. Many web apps load their data as JSON – this is often the cleanest way to get it.
actionslistUp to 30 steps that are carried out in order, see below.

Steps: click, type, keys, select, scripts

Each step is an object with exactly one of these forms, plus optionally "optional": true and "timeout_ms": 100–30000:

StepWhat it does
{"click": "selector"}Clicks the first visible element that matches.
{"type": "selector", "text": "…"}Types the text (up to 2,000 characters) into the element.
{"press": "Enter"}Presses a key: Enter, Tab, Escape, Backspace, Delete, ArrowDown, ArrowUp, ArrowLeft, ArrowRight, PageDown, PageUp, Home, End, Space or a single character.
{"hover": "selector"}Moves the mouse over the element, for menus that open on hover.
{"select": "selector", "value": "…"}Chooses the option with this value in a <select> and lets the page know.
{"scroll_to": "selector"}Scrolls the element into view, for content that loads when it becomes visible.
{"scroll": 2}Scrolls to the bottom 1 to 20 times.
{"wait_for": "selector"}Waits until such an element is visible.
{"wait_for_hidden": "selector"}Waits until the element is gone, for example a loading spinner.
{"wait_for_navigation": true}Waits until the next page has loaded, after a click that opens one.
{"wait_ms": 1500}Waits 1 to 15,000 milliseconds.
{"evaluate": "…"}Runs JavaScript in the page (up to 20,000 characters). The value of the expression comes back in steps[i].value as JSON; promises are awaited. Example: "[...document.querySelectorAll("h2")].map(e => e.textContent)".
{"goto": "https://…"}Opens another address in the same browser, with the cookies collected so far.

Optional steps. A step with "optional": true is skipped when its element does not show up within its time limit (default 5 seconds) – made for cookie banners that only appear sometimes. A required step waits up to 10 seconds by default; if it fails, the remaining steps are skipped, you still get the page, and steps shows which step failed.

curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://httpbin.org/forms/post",
    "render": {
      "actions": [
        {
          "click": "#cookie-accept",
          "optional": true,
          "timeout_ms": 2000
        },
        {
          "type": "input[name=\"custname\"]",
          "text": "Ada Lovelace"
        },
        {
          "click": "input[value=\"large\"]"
        },
        {
          "evaluate": "document.querySelector('\''input[name=\"custname\"]'\'').value"
        },
        {
          "click": "button"
        },
        {
          "wait_for_navigation": true
        }
      ],
      "screenshot": true
    }
  }'
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://httpbin.org/forms/post",
        "render": {
            "actions": [
                {
                    "click": "#cookie-accept",
                    "optional": True,
                    "timeout_ms": 2000,
                },
                {"type": "input[name=\"custname\"]", "text": "Ada Lovelace"},
                {"click": "input[value=\"large\"]"},
                {
                    "evaluate": "document.querySelector('input[name=\"custname\"]').value",
                },
                {"click": "button"},
                {"wait_for_navigation": True},
            ],
            "screenshot": True,
        },
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
for step in data["steps"]:
    print(step)
print(data["final_url"])  # the page after the form was sent
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://httpbin.org/forms/post",
    render: {
      actions: [
        { click: "#cookie-accept", optional: true, timeout_ms: 2000 },
        { type: "input[name=\"custname\"]", text: "Ada Lovelace" },
        { click: "input[value=\"large\"]" },
        {
          evaluate: "document.querySelector('input[name=\"custname\"]').value",
        },
        { click: "button" },
        { wait_for_navigation: true },
      ],
      screenshot: true,
    },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
for (const step of data.steps) console.log(step);
console.log(data.final_url); // the page after the form was sent
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://httpbin.org/forms/post",
    "render": {
        "actions": [
            {
                "click": "#cookie-accept",
                "optional": True,
                "timeout_ms": 2000,
            },
            {"type": "input[name=\"custname\"]", "text": "Ada Lovelace"},
            {"click": "input[value=\"large\"]"},
            {
                "evaluate": "document.querySelector('input[name=\"custname\"]').value",
            },
            {"click": "button"},
            {"wait_for_navigation": True},
        ],
        "screenshot": 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://httpbin.org/forms/post",
  render: {
    actions: [
      { click: "#cookie-accept", optional: true, timeout_ms: 2000 },
      { type: "input[name=\"custname\"]", text: "Ada Lovelace" },
      { click: "input[value=\"large\"]" },
      {
        evaluate: "document.querySelector('input[name=\"custname\"]').value",
      },
      { click: "button" },
      { wait_for_navigation: true },
    ],
    screenshot: 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://httpbin.org/forms/post",
        "render" => [
            "actions" => [
                [
                    "click" => "#cookie-accept",
                    "optional" => true,
                    "timeout_ms" => 2000,
                ],
                ["type" => "input[name=\"custname\"]", "text" => "Ada Lovelace"],
                ["click" => "input[value=\"large\"]"],
                [
                    "evaluate" => "document.querySelector('input[name=\"custname\"]').value",
                ],
                ["click" => "button"],
                ["wait_for_navigation" => true],
            ],
            "screenshot" => 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["steps"], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
echo $data["final_url"], PHP_EOL;
package main

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

func main() {
	payload := []byte(`{
  "url": "https://httpbin.org/forms/post",
  "render": {
    "actions": [
      {
        "click": "#cookie-accept",
        "optional": true,
        "timeout_ms": 2000
      },
      {
        "type": "input[name=\"custname\"]",
        "text": "Ada Lovelace"
      },
      {
        "click": "input[value=\"large\"]"
      },
      {
        "evaluate": "document.querySelector('input[name=\"custname\"]').value"
      },
      {
        "click": "button"
      },
      {
        "wait_for_navigation": true
      }
    ],
    "screenshot": 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["steps"])
	fmt.Println(data["final_url"])
}
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://httpbin.org/forms/post",
  "render" => {
    "actions" => [
      {
        "click" => "#cookie-accept",
        "optional" => true,
        "timeout_ms" => 2000,
      },
      {
        "type" => "input[name=\"custname\"]",
        "text" => "Ada Lovelace",
      },
      { "click" => "input[value=\"large\"]" },
      {
        "evaluate" => "document.querySelector('input[name=\"custname\"]').value",
      },
      { "click" => "button" },
      { "wait_for_navigation" => true },
    ],
    "screenshot" => 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)
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://httpbin.org/forms/post",
              "render": {
                "actions": [
                  {
                    "click": "#cookie-accept",
                    "optional": true,
                    "timeout_ms": 2000
                  },
                  {
                    "type": "input[name=\\"custname\\"]",
                    "text": "Ada Lovelace"
                  },
                  {
                    "click": "input[value=\\"large\\"]"
                  },
                  {
                    "evaluate": "document.querySelector('input[name=\\"custname\\"]').value"
                  },
                  {
                    "click": "button"
                  },
                  {
                    "wait_for_navigation": true
                  }
                ],
                "screenshot": 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://httpbin.org/forms/post",
      "render": {
        "actions": [
          {
            "click": "#cookie-accept",
            "optional": true,
            "timeout_ms": 2000
          },
          {
            "type": "input[name=\"custname\"]",
            "text": "Ada Lovelace"
          },
          {
            "click": "input[value=\"large\"]"
          },
          {
            "evaluate": "document.querySelector('input[name=\"custname\"]').value"
          },
          {
            "click": "button"
          },
          {
            "wait_for_navigation": true
          }
        ],
        "screenshot": 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);

Only when needed: "render": "auto"

"render": "auto" first fetches the page without a browser. Only when that answer is an error status (401, 403, 429, 503), a page that needs a browser to show its content, a page that is only a JavaScript shell, a page without the element render_options.wait_for waits for, or when extract found nothing, it is fetched again in the browser. You pay for the answer you get: the first try is free when it is not the answer, and the browser part (9 credits) only when the browser was needed.

Request
{
  "url": "https://shop.example/p/42",
  "render": "auto",
  "render_options": {
    "wait_for": ".price"
  },
  "extract": {
    "price": ".price"
  }
}

The answer says what happened: "strategy": "http" or "browser", and strategy_attempts lists each try with its status, the reason for the second (blocked_status, challenge_page, javascript_shell, wait_for_missing – the element render_options.wait_for names is not in the plain page –, nothing_extracted, no_answer) and its credits. Browser settings for the second try go into render_options (the options of render); screenshots, PDFs, steps and captured requests need the browser every time – use render: {…} for those. max_credits counts the browser part.

See every step: render.trace

"trace": true in render returns trace: a small picture (JPEG, up to 800 pixels wide) after every step of actions and at the end, each with the time, the address and the page's console messages. Use it to see where a sequence of clicks went wrong. At most 25 pictures; free.

Background requests

Many pages load their actual data afterwards, as JSON. With capture you get those answers directly, without parsing the HTML:

curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://quotes.toscrape.com/scroll",
    "render": {
      "capture": [
        "/api/quotes"
      ],
      "wait_until": "networkidle"
    }
  }'
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/scroll",
        "render": {"capture": ["/api/quotes"], "wait_until": "networkidle"},
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
import json
for c in data["captured"]:
    print(c["status"], c["url"])
    print(json.loads(c["body"])["quotes"][0]["text"])
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/scroll",
    render: { capture: ["/api/quotes"], wait_until: "networkidle" },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
for (const c of data.captured) {
  console.log(c.status, c.url);
  console.log(JSON.parse(c.body).quotes[0].text);
}
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://quotes.toscrape.com/scroll",
    "render": {"capture": ["/api/quotes"], "wait_until": "networkidle"},
})
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/scroll",
  render: { capture: ["/api/quotes"], wait_until: "networkidle" },
});
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/scroll",
        "render" => ["capture" => ["/api/quotes"], "wait_until" => "networkidle"],
    ], 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["captured"], 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/scroll",
  "render": {
    "capture": [
      "/api/quotes"
    ],
    "wait_until": "networkidle"
  }
}`)
	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["captured"])
}
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/scroll",
  "render" => { "capture" => ["/api/quotes"], "wait_until" => "networkidle" },
})

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/scroll",
              "render": {
                "capture": [
                  "/api/quotes"
                ],
                "wait_until": "networkidle"
              }
            }
            """;
        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/scroll",
      "render": {
        "capture": [
          "/api/quotes"
        ],
        "wait_until": "networkidle"
      }
    }
    """;
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);

In which order things happen

  1. The device is set up (see Device and environment), cookies and stored values are put in place.
  2. The page loads until wait_until is reached.
  3. wait_for, if given, then scroll.
  4. The actions, one after the other.
  5. wait_ms, if given.
  6. The HTML is taken, then screenshot, PDF and the captured requests.

All of this has to fit into the request's timeout (timeout_ms, at most your plan's). If the element in wait_for never appears, the request ends with timeout and costs nothing.

Browser, language, headers and cookies

Cost

Rendering adds 9 credits to the usual price: a rendered page up to 1 MB costs 10 credits. bytes.down counts everything the browser loaded for the page, scripts and styles included, so blocking images, media and fonts (the default) and trackers (block_urls) keeps the price down. Screenshots, PDFs, steps and captured requests cost nothing extra. Requests that fail cost nothing.

Try a plain request first. If it already contains what you need, it is ten times cheaper and much faster.

Limits

Was this page helpful?

Last updated