selenium 怎样在不关闭的情况下更换代理 IP?

也可以这么讲:在不关闭的情况下更换 option 里面的 IP,更换 UA ?

没有使用爬虫架构,直接使用 python+selenium 编写固定行为的爬虫,现需要整合多线程和IP代理池,不想new selenium 新打开浏览器。

阅读 8.8k
1 个回答

可以用js注入的方式动态更换IP
以下是Firefox的Python代码:

def change_ip(driver):

ip = get_ip()#ip格式"127.0.0.1:80"
driver.get("about:config");
#js代码
setupScript = '''var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
prefs.setIntPref("network.proxy.type", 1);
prefs.setCharPref("network.proxy.http", "%s");
prefs.setIntPref("network.proxy.http_port", "%s");
prefs.setCharPref("network.proxy.ssl", "%s");
prefs.setIntPref("network.proxy.ssl_port", "%s");
prefs.setCharPref("network.proxy.ftp", "$%s");
prefs.setIntPref("network.proxy.ftp_port", "%s");
''' % (ip.split(':')[0], ip.split(':')[1], ip.split(':')[0], ip.split(':')[1], ip.split(':')[0], ip.split(':')[1])
#执行js
driver.execute_script(setupScript);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进