You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Puppeteer实现带用户名密码的Socks5代理认证?

在Puppeteer中使用带用户名密码的Socks5代理的可行方案

直接利用Chrome原生命令行参数配置带认证的Socks5代理是最可靠的方案,无需依赖第三方包,且能完美支持用户名密码验证。

核心实现方式

启动Puppeteer时,通过args参数传入--proxy-server,格式为socks5://用户名:密码@代理地址:端口,Chrome会自动处理Socks5的认证流程。

代码示例

const puppeteer = require('puppeteer');

(async () => {
  // 替换为你的代理信息
  const proxyUsername = 'your-proxy-user';
  const proxyPassword = 'your-proxy-pass';
  const proxyHost = 'proxy.example.com';
  const proxyPort = 1080;

  // 特殊字符URL编码:如果用户名/密码包含@、:、/等,必须编码否则解析失败
  const encodedUser = encodeURIComponent(proxyUsername);
  const encodedPass = encodeURIComponent(proxyPassword);
  const proxyUrl = `socks5://${encodedUser}:${encodedPass}@${proxyHost}:${proxyPort}`;

  const browser = await puppeteer.launch({
    args: [
      `--proxy-server=${proxyUrl}`,
      // 可选:绕过本地地址代理(访问localhost时不使用代理)
      '--proxy-bypass-list=<-loopback>'
    ]
  });

  const page = await browser.newPage();
  // 验证代理是否生效
  await page.goto('https://httpbin.org/ip');
  console.log('当前代理IP:', await page.$eval('pre', el => el.textContent));

  await browser.close();
})();

逐页切换不同Socks5代理的方案

如果需要为不同页面使用不同的带认证Socks5代理,可以通过创建独立的浏览器上下文实现:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();

  // 上下文1:使用代理A
  const contextA = await browser.createIncognitoBrowserContext({
    proxyServer: `socks5://${encodeURIComponent('userA')}:${encodeURIComponent('passA')}@proxyA.com:1080`
  });
  const pageA = await contextA.newPage();
  await pageA.goto('https://httpbin.org/ip');
  console.log('代理A的IP:', await pageA.$eval('pre', el => el.textContent));

  // 上下文2:使用代理B
  const contextB = await browser.createIncognitoBrowserContext({
    proxyServer: `socks5://${encodeURIComponent('userB')}:${encodeURIComponent('passB')}@proxyB.com:1080`
  });
  const pageB = await contextB.newPage();
  await pageB.goto('https://httpbin.org/ip');
  console.log('代理B的IP:', await pageB.$eval('pre', el => el.textContent));

  await contextA.close();
  await contextB.close();
  await browser.close();
})();

关于你提到的无效方案说明

  • proxy-chain包仅支持HTTP/HTTPS代理的转发处理,确实不支持Socks5协议,因此无法用于你的场景。
  • page.authenticate()方法的作用是对HTTP/HTTPS网站进行身份验证(比如网站弹出的登录框),而非代理服务器的认证,所以对Socks5代理完全无效。

内容的提问来源于stack exchange,提问作者todel23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:15:47