Proxys in Puppeteer und Playwright einrichten
Eine Schritt-für-Schritt-Anleitung zum Anbinden von Proxys an Puppeteer und Playwright mit JavaScript-Codebeispielen, Fehlerbehandlung und IP-Rotation innerhalb der Session.
Puppeteer: grundlegende Integration
Die einfachste Möglichkeit ist, den Proxy beim Start des Browsers über args zu übergeben:
const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({
args: [
'--proxy-server=http://gate.proxyprovider.com:7777',
'--no-sandbox'
]
});
const page = await browser.newPage();
await page.goto('https://api.ipify.org');
console.log(await page.content()); // your new IP
Puppeteer: mit Authentifizierung
Die meisten Anbieter erfordern eine user:pass-Authentifizierung. Puppeteer unterstützt sie nicht direkt über args, verwende daher page.authenticate():
const page = await browser.newPage();
await page.authenticate({
username: 'your-username',
password: 'your-password'
});
await page.goto('https://target.com');
Bei Residential-Anbietern enthält das user:pass-Format üblicherweise Session-Parameter:
// Decodo: sticky 30 min, US gateway
username: 'user-spXXXX-country-us-session-abc123'
password: 'your-password'
// SOAX: sticky 1 hour, package id
username: 'package-XXX-country-us-sessionid-abc'
password: 'your-password'
Playwright: Einrichtung
Die API von Playwright ist etwas komfortabler — der Proxy wird in den Browser-Context übergeben:
const { chromium } = require('playwright');
const browser = await chromium.launch();
const context = await browser.newContext({
proxy: {
server: 'http://gate.proxyprovider.com:7777',
username: 'your-username',
password: 'your-password'
}
});
const page = await context.newPage();
await page.goto('https://api.ipify.org');
IP-Rotation im Code
Für die Rotation innerhalb eines einzelnen Skripts erstellst du für jeden "work batch" einen neuen Context:
async function scrapeUrls(urls) {
for (const url of urls) {
const context = await browser.newContext({
proxy: { server: getNextProxy() } // your rotation function
});
const page = await context.newPage();
await page.goto(url);
// ... process
await context.close(); // releases the IP
}
}
Traffic-Optimierung
Die größte Einsparung besteht darin, Medien und Skripte zu blockieren, die du nicht brauchst:
await page.setRequestInterception(true);
page.on('request', req => {
const resourceType = req.resourceType();
if (['image', 'stylesheet', 'font', 'media'].includes(resourceType)) {
req.abort();
} else {
req.continue();
}
});
Auf Websites wie Amazon spart das 60–80% der Bandbreite und macht aus einer Aufgabe mit 10 GB/Tag eine mit 2–3 GB/Tag. Bei Anbietern mit Abrechnung pro GB ist das eine Kostenersparnis von 3–4×.
Achtung: Das vollständige Blockieren von JS kann React-/SPA-Seiten beschädigen. Blockiere dort nur image, font und media — und behalte stylesheet und script bei.