Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set proxy for selenium chrome driver in ruby

Browsermob proxy:-

https://github.com/jarib/browsermob-proxy-rb

I can able to create and set proxy for firefox profile but not on chrome.

I don't know which options i have to use for chrome to set proxy.

Am using the following code:-

For firefox:-

require 'selenium/webdriver'
require 'browsermob/proxy'

server = BrowserMob::Proxy::Server.new("/path/to/downloads/browsermob-proxy/bin/browsermob-proxy") #=> #<BrowserMob::Proxy::Server:0x000001022c6ea8 ...>
server.start

proxy = server.create_proxy #=> #<BrowserMob::Proxy::Client:0x0000010224bdc0 ...>

profile = Selenium::WebDriver::Firefox::Profile.new #=> #<Selenium::WebDriver::Firefox::Profile:0x000001022bf748 ...>
profile.proxy = proxy.selenium_proxy

driver = Selenium::WebDriver.for :firefox, :profile => profile

proxy.new_har "google"
driver.get "http://google.com"

har = proxy.har #=> #<HAR::Archive:0x-27066c42d7e75fa6>
har.entries.first.request.url #=> "http://google.com"
har.save_to "/tmp/google.har"

proxy.close
driver.quit

For chrome:-

require 'selenium/webdriver'
require 'browsermob/proxy'

server = BrowserMob::Proxy::Server.new("/path/to/downloads/browsermob-proxy/bin/browsermob-proxy") #=> #<BrowserMob::Proxy::Server:0x000001022c6ea8 ...>
server.start

proxy = server.create_proxy #=> #<BrowserMob::Proxy::Client:0x0000010224bdc0 ...>

profile = Selenium::WebDriver::Chrome::Profile.new #=>
profile.proxy = proxy.selenium_proxy

driver = Selenium::WebDriver.for :chrome, :prefs => profile

proxy.new_har "google"
driver.get "http://google.com"

har = proxy.har #=> #<HAR::Archive:0x-27066c42d7e75fa6>
har.entries.first.request.url #=> "http://google.com"
har.save_to "/tmp/google.har"

proxy.close
driver.quit

In chrome, errors throws on the following line

profile.proxy = proxy.selenium_proxy

Error:- NoMethodError: undefined method `proxy=' for #

How to set proxy on chrome driver profile ?

like image 846
Galet Avatar asked Nov 01 '22 08:11

Galet


1 Answers

Hey not sure if resolve this issue already, I faced same problem but finally got that work by using this code:

require 'selenium/webdriver'
require 'browsermob/proxy'

server = BrowserMob::Proxy::Server.new("/path/to/downloads/browsermob-proxy/bin/browsermob-proxy") #=> #<BrowserMob::Proxy::Server:0x000001022c6ea8 ...>
server.start

proxy = Selenium::WebDriver::Proxy.new(:http => @proxy.selenium_proxy.http)
caps = Selenium::WebDriver::Remote::Capabilities.chrome(:proxy => proxy)
driver = Selenium::WebDriver.for(:chrome, :desired_capabilities => caps)

Then you can save the har file using har= proxy.har

By using this basically you avoiding to chromedriver to point to wrong port and localhost. Also this approach works also on IEdriver just change the caps to

Selenium::WebDriver::Remote::Capabilities.internetexplorer(:proxy => proxy)

Hope this approach helps :)

like image 64
mcbuddy Avatar answered Nov 15 '22 05:11

mcbuddy