통합

Shifter와 함께 사용 Cheerio

Shifter의 레지덴셜 및 ISP 프록시를 Cheerio와 페어링하여 빠르고 가벼운 Node 스크래핑을 구현하세요. Cheerio는 jQuery 스타일 HTML 파싱을 처리하고 Shifter는 레지덴셜 IP를 처리하므로, 헤드리스 브라우저가 필요하지 않습니다.

빠른 시작

설치

npm install cheerio axios https-proxy-agent

기본 사용법

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"));
});

기능

axios, got, got-scraping, undici 및 프록시 URL을 지원하는 모든 HTTP 클라이언트와 깔끔하게 호환됩니다
기본값은 요청별 로테이션이며, 스티키 세션에는 `sid`를, N초 동안의 시간제 고정에는 `ttl-N`을 사용합니다
Crawlee, Apify 및 프록시 URL을 지원하는 모든 프로덕션 크롤러 프레임워크와 호환
사용자 이름 매개변수를 통한 195개국 이상 Geo 타겟팅 - country, region, city, ASN
정적 또는 JS 부담이 적은 대상에 대해 헤드리스 브라우저 스크래핑보다 자릿수 단위로 더 빠름
TypeScript, ESM, CommonJS 및 14 이상의 모든 Node.js LTS와 호환

예시

스티키 세션 + 다중 페이지 크롤링

다중 페이지 크롤링 기간 동안 레지덴셜 IP 하나를 고정하세요. 지역 타겟팅을 위해 `country-uk`를 추가하고, 고정 세션 창을 5분으로 연장하려면 `ttl-300`을 추가하세요.

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`);

병렬 스크래핑 (요청별 로테이션)

요청별 로테이션을 위해 sid를 제거하세요. 각 병렬 요청은 서로 다른 레지덴셜 IP를 사용하므로 IP당 속도 제한에 걸리지 않고 URL 목록을 처리하는 데 적합합니다.

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 (내장 브라우저 핑거프린트)

got-scraping은 got 위에 사실적인 헤더 생성 기능을 번들로 제공합니다. Shifter와 함께 사용하면 Puppeteer보다 100배 빠른, 작고 브라우저 형태의 HTTP 스크래퍼를 만들 수 있습니다.

// 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(Shifter를 활용한 프로덕션 크롤러)

Crawlee(Apify 제공)는 큐, 재시도, 지속성, 프록시 로테이션을 기본적으로 처리합니다. Shifter를 ProxyConfiguration으로 연결하면 나머지는 Crawlee가 처리합니다.

// 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",
]);
자주 묻는 질문

자주 묻는 질문

Cheerio와 Shifter 사용에 관한 일반적인 질문.

아니요. Cheerio는 파서이며 HTTP 요청을 직접 만들지 않습니다. 프록시는 Cheerio와 함께 사용하는 HTTP 클라이언트(axios, got, undici, fetch)에 설정합니다. Shifter를 통해 HTML을 가져온 후에는 평소처럼 Cheerio의 load() 함수에 전달하면 됩니다.

p.shifter.io:443을 가리키는 https-proxy-agent로 axios를 구성하세요(자격 증명 인라인 포함). 페이지를 가져와서 response.data를 cheerio.load()에 전달한 다음 jQuery처럼 쿼리하세요. 전체 설정은 약 10줄의 코드입니다.

필요한 데이터가 초기 HTML 페이로드에 있을 때는 항상 Cheerio를 사용하세요. 헤드리스 Chrome보다 10배에서 100배 빠르며 메모리 사용량도 훨씬 적습니다. 페이지가 JavaScript를 통해 클라이언트 측에서 콘텐츠를 하이드레이션할 때만 Puppeteer나 Playwright로 전환하세요.

프록시 사용자 이름에 세션 ID를 추가하세요(예: `customer-USERNAME-country-us-sid-123ABC`). 크롤링 실행 중 모든 fetch에서 동일한 axios 인스턴스를 재사용하면 Shifter가 계속 동일한 레지덴셜 IP를 반환합니다. `ttl-N`을 추가하면 수명을 연장할 수 있습니다.

예. Crawlee에는 큐잉, 재시도, 동시성을 처리하는 CheerioCrawler가 내장되어 있습니다. 세션마다 고유한 sid가 포함된 새로운 Shifter URL을 반환하는 newUrlFunction과 함께 Crawlee의 ProxyConfiguration을 통해 Shifter를 구성하세요.

예. got-scraping은 `proxyUrl` 옵션을 지원하며 프록시 협상을 투명하게 처리합니다. 실제 브라우저 핑거프린트를 모방하는 내장 헤더 생성기와 결합하면 헤드리스 브라우저의 훌륭한 경량 대안이 됩니다.

시작하기

Shifter 사용을 함께 시작하기 Cheerio

Shifter의 205M+ 레지덴셜 및 ISP 프록시를 Cheerio와 페어링하여 빠르고 가벼운 Node 스크래핑을 구현하세요. 요청별 로테이션, 스티키 세션, 완전한 Crawlee 지원까지 제공합니다.

Shifter 무료로 체험하기몇 분 만에 설정. 언제든지 취소 가능.