Integración

Usa Shifter con Cheerio

Combina los proxies residenciales e ISP de Shifter con Cheerio para un scraping en Node rápido y ligero. Cheerio se encarga del análisis HTML al estilo jQuery y Shifter gestiona las IPs residenciales, sin necesidad de navegador sin interfaz gráfica.

Inicio rápido

Instalar

npm install cheerio axios https-proxy-agent

Uso básico

import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
import { load } from "cheerio";

const proxyUrl =
  "customer-USERNAME-country-us-sid-123ABC:PASSWORD@p.shifter.io:443";

const { data: html } = await axios.get("https://example.com", {
  httpsAgent: new HttpsProxyAgent(proxyUrl),
  proxy: false,
});

const $ = load(html);
console.log($("h1").text());

$("article.post").each((_, el) => {
  console.log($(el).find("h2").text(), "->", $(el).find("a").attr("href"));
});

Características

Compatible con axios, got, got-scraping, undici y cualquier cliente HTTP que admita una URL de proxy
Rotación por solicitud de forma predeterminada, con `sid` para sesiones persistentes y `ttl-N` para fijar IPs durante N segundos
Compatible con Crawlee, Apify y cualquier framework de crawler de producción que acepte una URL de proxy
Geolocalización en más de 195 países mediante parámetros de usuario -- país, región, ciudad, ASN
Significativamente más rápido que el scraping con navegadores sin interfaz gráfica para objetivos estáticos o con poco JavaScript
Compatible con TypeScript, ESM, CommonJS y todas las versiones LTS de Node.js desde la 14 en adelante

Ejemplos

Sesión persistente + rastreo multipágina

Fija una IP residencial durante todo un rastreo multipágina. Añade `country-uk` para segmentación geográfica y `ttl-300` para ampliar la ventana de sesión persistente a 5 minutos.

import axios, { type AxiosInstance } from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
import { load } from "cheerio";
import { randomBytes } from "node:crypto";

function makeClient(country: string): AxiosInstance {
  const sid = randomBytes(4).toString("hex");
  const proxyUrl =
    `customer-USERNAME-country-${country}-sid-${sid}-ttl-300:` +
    `PASSWORD@p.shifter.io:443`;

  return axios.create({
    httpsAgent: new HttpsProxyAgent(proxyUrl),
    proxy: false,
    timeout: 30_000,
    headers: {
      "User-Agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
      "Accept-Language": "en-US,en;q=0.9",
    },
  });
}

const client = makeClient("uk");

let url: string | null = "https://example.co.uk/products";
const products: { title: string; price: string }[] = [];

while (url) {
  const { data: html } = await client.get(url);
  const $ = load(html);

  $(".product-card").each((_, el) => {
    products.push({
      title: $(el).find("h2").text().trim(),
      price: $(el).find(".price").text().trim(),
    });
  });

  const next = $("a.next-page").attr("href");
  url = next ? new URL(next, url).toString() : null;
}

console.log(`Scraped ${products.length} products`);

Scraping en paralelo (rotación por solicitud)

Elimina el sid para rotación por solicitud. Cada solicitud en paralelo obtiene una IP residencial diferente, ideal para acceder a una lista de URLs sin activar los límites de velocidad por IP.

import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
import { load } from "cheerio";

function rotatingClient() {
  // No sid -> Shifter rotates the residential IP per request.
  const proxyUrl =
    "customer-USERNAME-country-us:PASSWORD@p.shifter.io:443";

  return axios.create({
    httpsAgent: new HttpsProxyAgent(proxyUrl),
    proxy: false,
    timeout: 30_000,
  });
}

async function scrape(url: string) {
  const client = rotatingClient();
  const { data: html } = await client.get(url);
  const $ = load(html);

  return {
    url,
    title: $("h1").first().text().trim(),
    headings: $("h2").map((_, el) => $(el).text().trim()).get(),
  };
}

const urls = [
  "https://example.com/category/laptops",
  "https://example.com/category/phones",
  "https://example.com/category/tablets",
  "https://example.com/category/wearables",
];

const results = await Promise.all(urls.map(scrape));
console.log(results);

got-scraping (huellas digitales de navegador integradas)

got-scraping incluye generación de cabeceras realistas sobre got. Combínalo con Shifter para obtener un scraper HTTP ligero con apariencia de navegador que sigue siendo 100 veces más rápido que Puppeteer.

// npm install got-scraping cheerio
import { gotScraping } from "got-scraping";
import { load } from "cheerio";

const proxyUrl =
  "customer-USERNAME-country-de-city-berlin-sid-456DEF:PASSWORD@p.shifter.io:443";

const html = await gotScraping({
  url: "https://example.de/products",
  proxyUrl,
  headerGeneratorOptions: {
    browsers: [{ name: "chrome", minVersion: 120 }],
    devices: ["desktop"],
    locales: ["de-DE", "en"],
    operatingSystems: ["macos", "linux"],
  },
}).text();

const $ = load(html);

$(".product").each((_, el) => {
  console.log({
    title: $(el).find("h2").text().trim(),
    price: $(el).find(".price").text().trim(),
  });
});

Crawlee (crawler de producción con Shifter)

Crawlee (de Apify) gestiona colas, reintentos, persistencia y rotación de proxies de forma nativa. Conecta Shifter como ProxyConfiguration y deja que Crawlee se encargue del resto.

// npm install crawlee cheerio
import { CheerioCrawler, ProxyConfiguration } from "crawlee";

const proxyConfiguration = new ProxyConfiguration({
  newUrlFunction: () => {
    // New residential IP per session. Crawlee rotates sessions
    // automatically on bans, so stale IPs get cycled out.
    const sid = Math.random().toString(36).slice(2, 10);
    return `customer-USERNAME-country-fr-sid-${sid}:PASSWORD@p.shifter.io:443`;
  },
});

const crawler = new CheerioCrawler({
  proxyConfiguration,
  maxConcurrency: 8,
  async requestHandler({ request, $, enqueueLinks, log }) {
    log.info(`${request.url} -> ${$("h1").text().trim()}`);

    $(".article").each((_, el) => {
      log.info(`  ${$(el).find("h2").text().trim()}`);
    });

    await enqueueLinks({ selector: "a.next-page", strategy: "same-domain" });
  },
});

await crawler.run([
  "https://example.fr/blog",
  "https://example.fr/news",
]);
Preguntas frecuentes

Preguntas frecuentes

Preguntas frecuentes sobre el uso de Shifter con Cheerio.

No. Cheerio es un analizador sintáctico y no realiza solicitudes HTTP. El proxy se configura en el cliente HTTP que uses junto con Cheerio (axios, got, undici, fetch). Una vez obtenido el HTML a través de Shifter, se lo pasas a la función load() de Cheerio de la forma habitual.

Comenzar

Empieza a usar Shifter con Cheerio

Combina los más de 205M de proxies residenciales y de ISP de Shifter con Cheerio para un scraping en Node rápido y ligero. Rotación por solicitud, sesiones persistentes y soporte completo para Crawlee.

Prueba Shifter gratisConfiguración en minutos. Cancela cuando quieras.