如何为 Puppeteer 设置代理
Puppeteer 代理示例
import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const context = await browser.createIncognitoBrowserContext({
proxyServer: "http://127.0.0.1:8080"
});
const page = await context.newPage();
await page.goto('https://example.com/');
console.log(await page.content());
await browser.close();
})();
安装包:
$ npm i @proxyport/proxyport
实例化
ProxyPort
并调用 getProxy()
方法:import { ProxyPort } from '@proxyport/proxyport';
const proxyPort = new ProxyPort(<API_KEY>);
(async () => {
const proxy = await proxyPort.getProxy();
console.log(proxy);
})();
完成前面的步骤后,您应该拥有如下所示的代码:
import puppeteer from 'puppeteer';
import { ProxyPort } from '@proxyport/proxyport';
(async () => {
const proxyPort = new ProxyPort(<API_KEY>);
const proxy = await proxyPort.getProxy();
const browser = await puppeteer.launch();
const context = await browser.createIncognitoBrowserContext({
proxyServer: `http://${proxy}`
});
const page = await context.newPage();
await page.goto('https://example.com/');
console.log(await page.content());
await browser.close();
})();
在某些情况下,您可能会遇到这样的错误:
Error: net::ERR_TIMED_OUT at https://example.com/
发生这种情况是因为您使用的是免费的公共代理服务器。 要处理此错误,您可以使用重试方法。 以下是您可以如何做到这一点:
import puppeteer from 'puppeteer';
import { ProxyPort } from '@proxyport/proxyport';
(async () => {
const proxyPort = new ProxyPort(<API_KEY>);
const browser = await puppeteer.launch();
for (let i = 0; i < 10; i++) {
const proxy = await proxyPort.getProxy();
const context = await browser.createIncognitoBrowserContext({
proxyServer: `http://${proxy}`
});
const page = await context.newPage();
try {
await page.goto('https://example.com/');
console.log(await page.content());
break;
} catch (e) {
console.log(`failed to load page with proxy: ${proxy}, error: ${e}\n`);
}
}
await browser.close();
})();