集成

将Shifter与以下工具配合使用 Cheerio

将 Shifter 的住宅代理和 ISP 代理与 Cheerio 配合使用,实现快速、轻量的 Node.js 抓取。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`实现粘性会话,使用`ttl-N`实现N秒定时固定
兼容 Crawlee、Apify 及任何接受代理 URL 的生产级爬虫框架
通过用户名参数在 195+ 个国家/地区进行地理定向 — country、region、city、ASN
对于静态或轻JS目标,速度比无头浏览器抓取快一个数量级
兼容 TypeScript、ESM、CommonJS 以及 Node.js 14 及以上所有 LTS 版本

示例

粘性会话 + 多页爬取

在多页爬取过程中固定使用同一个住宅 IP。添加 `country-uk` 进行地理定向,添加 `ttl-300` 将粘性窗口延长至 5 分钟。

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,非常适合批量抓取 URL 列表而不触发单 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(内置浏览器指纹)

got-scraping 在 got 基础上集成了真实请求头生成功能。与 Shifter 配合使用,可构建一个体积小巧、具有浏览器特征的 HTTP 爬虫,速度仍比 Puppeteer 快 100 倍。

// 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",
]);
常见问题

常见问题

关于将 Shifter 与 Cheerio 搭配使用的常见问题。

不需要。Cheerio 是一个解析器,本身不发起 HTTP 请求。代理需在与 Cheerio 配合使用的 HTTP 客户端上配置(axios、got、undici、fetch)。通过 Shifter 获取 HTML 后,像往常一样将其传入 Cheerio 的 load() 函数即可。

立即开始

开始将Shifter与以下工具配合使用 Cheerio

将 Shifter 的 205M+ 住宅和 ISP 代理与 Cheerio 结合,实现快速、轻量的 Node.js 抓取。支持按请求轮换、粘性会话及完整的 Crawlee 集成。

免费试用 Shifter几分钟内完成设置,随时可取消。