在RSelenium中为Chrome Web Driver配置代理的方法
Great question! I’ve run into this exact frustration before—RSelenium doesn’t include a makeChromeProfile() function like it does for Firefox, but setting up a proxy for Chrome is totally doable using Chrome’s command-line arguments and RSelenium’s extraCapabilities parameter. Here are two reliable methods:
Method 1: Basic Proxy (No Authentication)
This works for HTTP/HTTPS or SOCKS5 proxies that don’t require a username and password.
Step-by-Step Code:
library(RSelenium) # Replace these with your actual proxy details proxy_host <- "your-proxy-address" proxy_port <- 1234 # Use the port your proxy uses # Set up Chrome options with proxy chrome_proxy_options <- list( chromeOptions = list( args = list( # For HTTP/HTTPS proxy paste0("--proxy-server=http://", proxy_host, ":", proxy_port), # Optional: Skip certificate errors if your proxy uses self-signed certs "--ignore-certificate-errors" ) ) ) # Launch Chrome with the proxy configuration remDr <- remoteDriver( browserName = "chrome", extraCapabilities = chrome_proxy_options ) remDr$open()
For SOCKS5 Proxies:
Just modify the --proxy-server argument to use the socks5:// protocol:
args = list( paste0("--proxy-server=socks5://", proxy_host, ":", proxy_port) )
Method 2: Proxy with Authentication (Advanced)
If your proxy requires a username and password, Chrome doesn’t support passing these directly via command-line arguments. Instead, you can create a tiny Chrome extension to inject the authentication credentials automatically.
Quick Extension Setup:
- Create a new folder (e.g.,
proxy-auth) with two files:manifest.json:{ "version": "1.0.0", "manifest_version": 2, "name": "Proxy Auth", "permissions": ["proxy", "tabs", "unlimitedStorage", "storage", "<all_urls>"], "background": { "scripts": ["background.js"] } }background.js:chrome.proxy.settings.set({value: { mode: "fixed_servers", rules: { singleProxy: { scheme: "http", // or "socks5" host: "your-proxy-address", port: 1234 } } }, scope: "regular"}, function() {}); chrome.webRequest.onAuthRequired.addListener( function(details) { return { authCredentials: { username: "your-proxy-username", password: "your-proxy-password" } }; }, {urls: ["<all_urls>"]}, ["blocking"] );
- Zip the folder into
proxy-auth.zip. - Load the extension in RSelenium:
chrome_proxy_options <- list( chromeOptions = list( args = list( paste0("--load-extension=", normalizePath("proxy-auth.zip")) ) ) ) remDr <- remoteDriver( browserName = "chrome", extraCapabilities = chrome_proxy_options ) remDr$open()
Why No makeChromeProfile()?
RSelenium’s makeFirefoxProfile() exists because Firefox uses a dedicated profile system for storing settings. Chrome, however, relies more on command-line arguments and extensions for custom configurations—so we use extraCapabilities to pass these directly to the ChromeDriver.
内容的提问来源于stack exchange,提问作者Yifu Yan

