Skip to content

Instantly share code, notes, and snippets.

@ArmandoAssuncao
Last active November 26, 2023 14:29
Show Gist options
  • Save ArmandoAssuncao/51edbbdc8dc2e8e6ac8c16c2847ed960 to your computer and use it in GitHub Desktop.
Save ArmandoAssuncao/51edbbdc8dc2e8e6ac8c16c2847ed960 to your computer and use it in GitHub Desktop.
Ruby Selenium with Proxy
# Obs: Work only in Firefox 66.x or prior, because the function "driver.switch_to.alert.send_keys" not work in new versions.
# tested in selenium-webdriver (3.142.7), webdrivers (4.6.0) and firefox (66.0.5)
# Download firefox to folder
# config/initializers/selenium.rb
Selenium::WebDriver::Firefox::Binary.path = 'path/to/firefox/66.x'
# -----------------------------------------------------------------------------------------------------
# Code
def your_code
proxy = {
addr: 'PROXY_ADDR',
port: 'PROXY_PORT',
user: 'PROXY_USER',
pass: 'PROXY_PASS',
}
driver = selenium_driver(proxy)
driver.navigate.to('https://api.myip.com')
puts driver.source_page
end
def selenium_driver(proxy)
profile = Selenium::WebDriver::Firefox::Profile.new
profile['network.proxy.type'] = 1
profile['network.proxy.http'] = proxy[:addr]
profile['network.proxy.http_port'] = proxy[:port].to_i
profile['network.proxy.ssl'] = proxy[:addr]
profile['network.proxy.ssl_port'] = proxy[:port].to_i
options = Selenium::WebDriver::Firefox::Options.new
options.profile = profile
options.add_argument('--headless') # optional
options.add_argument('--safe-mode') # optional
options.add_argument(
'--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
) # optional
driver = Selenium::WebDriver.for(:firefox, options: options)
# fill modal proxy auth.
sleep 3 # Necessary because prompt can delay to show.
driver.switch_to.alert.send_keys(
"#{proxy[:user]}#{Selenium::WebDriver::Keys::KEYS[:tab]}#{proxy[:pass]}"
)
driver.switch_to.alert.accept
driver
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment