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

如何在Ruby语言的Selenium框架中配置带身份验证的代理服务器

核心问题说明

Chrome的--proxy-server启动参数本身不支持嵌入用户名密码格式的代理地址,这是你之前直接拼接参数失效的根本原因。


方案1:使用Chrome扩展自动处理代理认证(推荐,适配绝大多数场景)

这个方案的原理是通过一个极简的自定义Chrome扩展,在触发代理认证请求时自动填充用户名和密码,无需手动操作,适配新版Chrome的headless模式。

完整Ruby实现代码

代码会动态生成临时扩展文件,使用完成后自动清理,无需手动维护扩展资源:

require 'selenium-webdriver'
require 'fileutils'

# 代理配置,替换为你的实际参数
proxy_host = '185.186.61.44'
proxy_port = '12323'
proxy_user = '7a2345129'
proxy_pass = 'easdga341d4'
# 代理协议,根据实际情况修改为http/socks5
proxy_scheme = 'http'

# 生成临时扩展目录
ext_dir = File.expand_path('tmp_proxy_ext')
FileUtils.mkdir_p(ext_dir)

# 写入扩展配置文件manifest.json
File.write(File.join(ext_dir, 'manifest.json'), <<~JSON)
{
  "version": "1.0.0",
  "manifest_version": 3,
  "name": "Proxy Auth Extension",
  "permissions": ["proxy", "webRequest", "webRequestAuthProvider"],
  "host_permissions": ["<all_urls>"],
  "background": {
    "service_worker": "background.js"
  },
  "minimum_chrome_version": "108"
}
JSON

# 写入代理认证逻辑文件background.js
File.write(File.join(ext_dir, 'background.js'), <<~JS)
const config = {
  mode: "fixed_servers",
  rules: {
    singleProxy: {
      scheme: "#{proxy_scheme}",
      host: "#{proxy_host}",
      port: parseInt(#{proxy_port})
    },
    bypassList: ["localhost", "127.0.0.1"]
  }
};

chrome.proxy.settings.set({value: config, scope: "regular"}, () => {});

chrome.webRequest.onAuthRequired.addListener(
  (details) => {
    return {
      authCredentials: {
        username: "#{proxy_user}",
        password: "#{proxy_pass}"
      }
    };
  },
  {urls: ["<all_urls>"]},
  ["blocking"]
);
JS

# 配置Selenium启动参数
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless=new') # 新版headless模式支持扩展
options.add_argument('--no-sandbox')
options.add_argument("--load-extension=#{ext_dir}") # 加载生成的代理认证扩展

driver = Selenium::WebDriver.for :chrome, options: options

# 测试代理是否生效,可替换为你要爬取的页面
driver.get('https://api.ipify.org')
puts "当前代理出口IP: #{driver.find_element(tag_name: 'body').text}"

# 退出驱动并清理临时扩展文件
driver.quit
FileUtils.rm_rf(ext_dir)

方案2:本地代理转发(适配旧版headless/不支持扩展的场景)

如果你的场景无法使用Chrome扩展(比如强制使用旧版headless模式),可以在本地搭建一个无认证的代理转发服务,将请求转发到带认证的远端代理,Selenium直接连接本地无认证代理即可。
常用的转发工具可选privoxy、tinyproxy,以privoxy为例:

  1. 安装privoxy后修改配置文件,添加转发规则:
forward / 185.186.61.44:12323 "7a2345129:easdga341d4"
  1. 启动privoxy(默认监听本地8118端口)
  2. Selenium直接配置本地无认证代理即可:
options.add_argument("--proxy-server=http://127.0.0.1:8118")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:45:03