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

Selenium切换IP地址代码无法正常运行问题求助

问题排查与解决方案

1. 修正代理地址格式

你的代理列表里第一个地址带了空格:"47.243.167.134 :8889",空格会导致Chrome无法正确解析代理地址,必须去掉空格,改成"47.243.167.134:8889"。

2. 验证代理有效性

免费代理网站的IP大多存活时间很短,你列的代理可能已经失效。可以先手动测试代理是否能正常访问目标网站,比如用curl命令:

curl -x http://47.243.167.134:8889 https://iplocation.com/

如果返回正常内容,说明代理可用;否则需要更换新的代理。

3. 适配新版Selenium的配置写法

Selenium 4+推荐使用ChromeOptions类来配置代理,而不是直接通过capabilities,这样兼容性更好。修改后的代码如下:

const {Builder, By, until} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

const proxies = [
  "47.243.167.134:8889",
  "154.236.179.233:1976",
  "200.105.215.22:33630",
];

async function changeIP() {
  try {
    const proxy = proxies[Math.floor(Math.random() * proxies.length)];
    const options = new chrome.Options();
    options.addArguments(`--proxy-server=http://${proxy}`);

    const driver = await new Builder()
      .forBrowser('chrome')
      .setChromeOptions(options)
      .build();

    await driver.get("https://iplocation.com/");
    // 验证IP是否切换成功
    const ipElement = await driver.wait(until.elementLocated(By.css('.ip-address')), 10000);
    const currentIp = await ipElement.getText();
    console.log('当前IP:', currentIp);

    // 可根据需求手动关闭浏览器
    // await driver.quit();
  } catch (error) {
    console.error('运行出错:', error.message);
  }
}

changeIP();

4. 添加错误处理与验证逻辑

原代码没有异常捕获,添加try/catch可以快速定位报错原因;同时通过获取页面IP元素,能直接验证代理是否生效。

额外注意事项

  • 确保ChromeDriver版本和你的Chrome浏览器版本匹配,版本不兼容会导致配置失效。
  • 部分免费代理需要验证(比如验证码),这类代理无法直接在Selenium中使用。
  • 频繁切换代理可能触发目标网站反爬机制,建议控制请求频率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:35:23