Um einen Proxy für Puppeteer in Node.js einzurichten, konfigurieren Sie die Browser-Startargumente mit --proxy-server=<proxy_address>:<port>, um den gesamten Browser-Traffic über den angegebenen Proxy zu leiten. Dies ermöglicht die Maskierung von IP-Adressen, geografisches Targeting oder das Umgehen von Ratenbegrenzungen und IP-Sperren bei automatisierten Web-Interaktionen.
Grundlegende Proxy-Konfiguration
Puppeteer steuert eine Chromium-Instanz und übergibt Proxy-Einstellungen direkt über Kommandozeilenargumente. Das primäre Argument ist --proxy-server.
Spezifizieren eines Proxy-Servers
Das Argument --proxy-server akzeptiert die Adresse und den Port des Proxys. Das Protokoll (HTTP, HTTPS, SOCKS4, SOCKS5) kann explizit definiert werden; HTTP wird typischerweise angenommen, wenn es weggelassen wird.
const puppeteer = require('puppeteer');
async function launchBrowserWithProxy(proxyAddress) {
const browser = await puppeteer.launch({
args: [
`--proxy-server=${proxyAddress}`,
// Optional: For extreme anonymity, consider disabling WebRTC
// '--disable-features=WebRTC'
],
headless: true, // or false for headful
});
const page = await browser.newPage();
return { browser, page };
}
async function runBasicProxyExample() {
const proxy = 'http://your-proxy-ip:port'; // Example: 'http://192.168.1.1:8080' or 'socks5://192.168.1.1:1080'
let browser;
try {
const { browser: launchedBrowser, page } = await launchBrowserWithProxy(proxy);
browser = launchedBrowser; // Assign to outer scope variable for finally block
await page.goto('https://httpbin.org/ip'); // A service to show your external IP
const ipInfo = await page.evaluate(() => document.body.textContent);
console.log('External IP through proxy:', ipInfo);
} catch (error) {
console.error('Error launching browser with proxy:', error);
} finally {
if (browser) {
await browser.close();
}
}
}
runBasicProxyExample();
Ersetzen Sie your-proxy-ip:port durch die tatsächliche IP-Adresse und den Port Ihres Proxy-Servers. Stellen Sie sicher, dass das Protokollpräfix (z.B. http://, socks5://) Ihrem Proxy-Typ entspricht.
Authentifizierte Proxys
Viele Proxy-Dienste erfordern eine Authentifizierung. Puppeteer handhabt dies über page.authenticate() nach der Browser- und Seiteninitialisierung, indem HTTP Basic Authentication Header an den Proxy gesendet werden.
Proxy-Authentifizierungsmethoden
page.authenticate(): Empfohlen für HTTP Basic Authentication mit Puppeteer.username:password@ip:portin--proxy-server: Während einige Tools dieses Format direkt unterstützen, istpage.authenticate()der Standard-Puppeteer-Ansatz für die Authentifizierung.
const puppeteer = require('puppeteer');
async function launchBrowserWithAuthenticatedProxy(proxyAddress, username, password) {
const browser = await puppeteer.launch({
args: [`--proxy-server=${proxyAddress}`],
headless: true,
});
const page = await browser.newPage();
// Authenticate with the proxy
await page.authenticate({ username, password });
return { browser, page };
}
async function runAuthenticatedProxyExample() {
const proxy = 'http://your-authenticated-proxy-ip:port';
const proxyUsername = 'your_username';
const proxyPassword = 'your_password';
let browser;
try {
const { browser: launchedBrowser, page } = await launchBrowserWithAuthenticatedProxy(proxy, proxyUsername, proxyPassword);
browser = launchedBrowser;
await page.goto('https://httpbin.org/ip');
const ipInfo = await page.evaluate(() => document.body.textContent);
console.log('External IP through authenticated proxy:', ipInfo);
} catch (error) {
console.error('Error with authenticated proxy:', error);
} finally {
if (browser) {
await browser.close();
}
}
}
runAuthenticatedProxyExample();
Proxy-Rotationsstrategien
Für groß angelegte Scraping-Aufgaben kann ein einzelner Proxy zu Ratenbegrenzungen führen. Die Proxy-Rotation beinhaltet das Wechseln zwischen mehreren Proxy-Servern, um Anfragen zu verteilen und die Anonymität zu wahren.
Implementierung der Proxy-Rotation
- Proxy-Liste pflegen: Speichern Sie verfügbare Proxys in einem Array, gegebenenfalls inklusive Authentifizierungsdetails.
- Auswahl-Logik: Implementieren Sie eine Strategie zur Auswahl eines Proxys für jede neue Browser-Instanz oder Anfrage. Gängige Strategien: Round-Robin, Zufällige Auswahl, Gewichtete Rotation.
const puppeteer = require('puppeteer');
// Example list of proxies, some with authentication details
const proxyConfigurations = [
{ address: 'http://proxy1.example.com:8080' },
{ address: 'http://auth-proxy1.example.com:8080', username: 'userA', password: 'passA' },
{ address: 'socks5://proxy3.