Налаштування проксі у Puppeteer
Додайте ротаційні проксі у скрапінг на headless Chrome з Puppeteer.
Puppeteer керує headless Chrome для скрапінгу сторінок із великою кількістю JavaScript. Задайте проксі під час запуску браузера - усі сторінки, які відкриває цей екземпляр браузера, йтимуть через SotaProxy.
Посібник із налаштування
Встановіть Puppeteer
npm install puppeteerPuppeteer автоматично встановлює вбудовану версію Chromium.
Запуск із проксі
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
args: ['--proxy-server=http://proxy.sotaproxy.com:10000'],
});
const page = await browser.newPage();
// Authenticate the proxy
await page.authenticate({
username: 'YOUR_USERNAME',
password: 'YOUR_PASSWORD',
});
await page.goto('https://httpbin.org/ip');
const content = await page.content();
console.log(content);
await browser.close();
})();Задайте --proxy-server в аргументах запуску і викличте page.authenticate() з вашими обліковими даними. Puppeteer вимагає задавати облікові дані на кожну сторінку, а не на браузер.
Гео-таргетинг
const browser = await puppeteer.launch({
args: ['--proxy-server=http://proxy.sotaproxy.com:10000'],
});
const page = await browser.newPage();
await page.authenticate({
username: 'YOUR_USERNAME_c_FR', // French IP
password: 'YOUR_PASSWORD',
});Додайте _c_XX до імені користувача в page.authenticate() для таргетингу на конкретну країну.
Автоматизуй через SotaProxy API
Усе описане вище працює без відкриття дашборда. З API-ключем Puppeteer може отримувати свіжі дані проксі, купувати нові та продовжувати ті, що спливають, - прямо з коду.
const API = 'https://api.sotaproxy.com/api/v1'
const H = { Authorization: 'Bearer sk_live_your_key' }
// Every active proxy on your account - no copy-pasting credentials
const { proxies } = await (await fetch(`${API}/proxies`, { headers: H })).json()
const p = proxies[0]
const proxyUrl = `http://${p.login}:${p.password}@${p.ip}:${p.portHttp}`
// Buy more when you scale (price-check first with POST /quote)
await fetch(`${API}/orders`, {
method: 'POST',
headers: { ...H, 'Content-Type': 'application/json', 'Idempotency-Key': 'my-unique-order-id' },
body: JSON.stringify({ product: 'ipv4', countryId: 565, periodId: '1m', quantity: 5 }),
})Why Puppeteer needs two steps
Chromium takes the proxy from a launch flag, and that flag has no place for credentials. Authentication happens afterwards, per page:
The proxy is set for the whole browser process, so one browser equals one address. Run several browsers when you need several identities in parallel.
One browser per address
Launch with the endpoint, then call page.authenticate before the first navigation:
Node: browser per identity
const puppeteer = require('puppeteer');
async function browserFor(sessionId) {
const browser = await puppeteer.launch({
args: ['--proxy-server=http://proxy.sotaproxy.com:10000'],
});
const page = await browser.newPage();
await page.authenticate({
username: `login_c_US_s_${sessionId}_ttl_1h`,
password: 'password',
});
return { browser, page };
}
const { page } = await browserFor(7);
await page.goto('https://example.com', { timeout: 30000 });- Call authenticate on every new page, not once per browser. A page opened later starts unauthenticated and the first request comes back 407.
- Use a separate user data directory per browser. Otherwise profiles share cookies and the address separation buys you nothing.
- Close browsers you are done with. Each one holds an open connection to our endpoint, and a leak here looks like a rate limit later.
- For many parallel identities, Playwright contexts are cheaper than Puppeteer browsers. Consider it when the count passes about ten.
Puppeteer specifics
Credentials in the launch flag do nothing
--proxy-server accepts a host and port only. Anything before the @ is dropped silently and you get 407.
One proxy per browser process
There is no per-context proxy. Rotating means launching another browser, which is why heavy rotation belongs in Playwright.
authenticate applies per page
New tabs and popups need their own call, and OAuth flows that open a popup break without it.
Headless detection is a separate problem
The proxy fixes the address, not the fingerprint. Pair it with stealth measures or an antidetect browser for account work.
Нотатки та поради
- •Puppeteer вимагає page.authenticate() для кожної нової сторінки. Playwright обробляє автентифікацію на рівні браузера (простіше для багатосторінкових сесій).
- •Розгляньте puppeteer-extra і puppeteer-extra-plugin-stealth для зниження детекції за відбитком.
- •Для високонавантаженого скрапінгу розгляньте Playwright - він чистіше обробляє конфігурацію проксі на кілька контекстів.
FAQ
У чому різниця між Puppeteer і Playwright для роботи з проксі?
Playwright підтримує конфігурацію проксі на рівні контексту браузера (чистіше для мультисесійних сетапів). Puppeteer вимагає автентифікації на кожну сторінку. Обидва працюють із SotaProxy.
Чи може Puppeteer впоратися з CAPTCHA?
Puppeteer не розв’язує CAPTCHA нативно. Резидентні проксі знижують частоту CAPTCHA. Для решти завдань інтегруйте сервіс розв’язання CAPTCHA (2Captcha, Anti-Captcha).
Схожі інтеграції
Отримай облікові дані проксі
Зареєструйся, поповни баланс і скопіюй ендпоінт у Puppeteer. Займе менше 5 хвилин.
Почати