How to specify the location of the chromedriver binary - ruby

Earlier I had put the Chrome binary, "chromedriver.exe", in the "C:/Windows" directory and Watir was picking it from there. Now I have to move my project to another machine so I can't hardcode the executable path. I also want the binary to be kept with our code on Git rather than making each test engineer manually update the binary as newer versions are released.
Now I have placed Chrome binary at a absolute path, but it is not being found. Here is what I tried (hooks.rb):
Before do
puts "inside hooks in before"
profile = Selenium::WebDriver::Chrome::Profile.new
profile['download.prompt_for_download'] = false
profile['download.default_directory'] = File.join(File.absolute_path('../..', File.dirname(__FILE__)),"browsers/chromedriver.exe")
#browser = Watir::Browser.new :chrome, :profile => profile
end
The output is:
inside hooks in before
Selenium::WebDriver::Error::WebDriverError: Unable to find the chromedriver executable. Please download the server from http://chromedriver.storage.googleapis.com/index.html and place it somewhere on your PATH. More info at http://code.google.com/p/selenium/wiki/ChromeDriver.
C:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/chrome/service.rb:21:in `executable_path'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/chrome/service.rb:34:in `default_service'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/chrome/bridge.rb:14:in `initialize'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/common/driver.rb:37:in `new'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/common/driver.rb:37:in `for'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver.rb:67:in `for'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.11/lib/watir-webdriver/browser.rb:46:in `initialize'
C:/Users/Admin/watircukepractice/test_puppies/features/support/hooks.rb:11:in `new'
C:/Users/Admin/watircukepractice/test_puppies/features/support/hooks.rb:11:in `Before'
I am on Windows 7, Using Ruby version 1.9.3p551 and I am referring to tutorial http://watirwebdriver.com/chrome/.
How do I tell Watir (and Selenium-WebDriver) the location of the chromedriver.exe?

Solution 1 - Selenium::WebDriver::Chrome.driver_path=
There is a Selenium::WebDriver::Chrome.driver_path= method that allows specifying of the chromedriver binary:
require 'watir'
# Specify the driver path
chromedriver_path = File.join(File.absolute_path('../..', File.dirname(__FILE__)),"browsers","chromedriver.exe")
Selenium::WebDriver::Chrome.driver_path = chromedriver_path
# Start the browser as normal
b = Watir::Browser.new :chrome
b.goto 'www.google.com'
b.close
Solution 2 - Specify :driver_path during browser initialization
As an alternative, you can also specify the driver path when initializing the browser. This is a bit nicer in that you do not need to have Selenium code, but would be repetitive if you initialize the browser in different places.
# Determine the driver path
chromedriver_path = File.join(File.absolute_path('../..', File.dirname(__FILE__)),"browsers","chromedriver.exe")
# Initialize the browser with the driver path
browser = Watir::Browser.new :chrome, driver_path: chromedriver_path
Solution 3 - Update ENV['PATH']
When I had originally answered this question, for whatever reason, I had not been able to get the above solution to work. Setting the value did not appear to be used when Selenium-WebDriver started the driver in. While the first solution is the recommended approach, this is an alternative.
Another option is to programmatically add the desired directory to the path, which is stored in the ENV['PATH']. You can see in the Selenium::WebDriver::Platform that the binary is located by checking if the executable exists in any of the folders in the path (from version 2.44.0):
def find_binary(*binary_names)
paths = ENV['PATH'].split(File::PATH_SEPARATOR)
binary_names.map! { |n| "#{n}.exe" } if windows?
binary_names.each do |binary_name|
paths.each do |path|
exe = File.join(path, binary_name)
return exe if File.executable?(exe)
end
end
nil
end
To specify the folder that includes the binary, you simply need to change the ENV['PATH'] (to append the directory):
require 'watir'
# Determine the directory containing chromedriver.exe
chromedriver_directory = File.join(File.absolute_path('../..', File.dirname(__FILE__)),"browsers")
# Add that directory to the path
ENV['PATH'] = "#{ENV['PATH']}#{File::PATH_SEPARATOR}#{chromedriver_directory}"
# Start the browser as normal
b = Watir::Browser.new :chrome
b.goto 'www.google.com'
b.close

In Selenium webdriver 3.x configs, change:
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"binary" => <path to chrome (example: chrome portable)>})
Capybara::Selenium::Driver.new(app, :browser => :chrome, :driver_path => <path to chrome driver>, :desired_capabilities => caps)
driver_path: Define path to chromedriver chromedriver page
binary: Define path to binary chrome app chromepage. You can use a chrome portable to use differents versions of chrome.

Update your Selenium driver_path directly.
Just call this before launching your new Chrome browser window:
Selenium::WebDriver::Chrome::Service.driver_path = Rails.root.join( "lib", "chromedriver" ).to_s
Of course, change the path to where your chromedriver is.
NOTE: driver_path needs to be a String, so don't pass in a File or Path object.

This works for me:
options = Selenium::WebDriver::Chrome::Options.new
Selenium::WebDriver::Chrome::Service.driver_path = '/app/.chromedriver/bin/chromedriver'
chrome_bin_path = ENV.fetch('GOOGLE_CHROME_SHIM', nil)
if chrome_bin_path
options.binary = chrome_bin_path if chrome_bin_path
options.add_argument '--no-sandbox'
options.add_argument '--window-size=1200x600'
options.add_argument '--headless'
options.add_argument '--disable-gpu'
end
browser = Watir::Browser.new(:chrome, options:)

Related

Chrome binary not found on Heroku with Selenium for Ruby on Rails

Two weeks ago, I managed to have a working environment on Heroku, combining Capybara, Selenium, Chromedriver and Chrome for web scraping. However, one week ago I must have changed something, which causes the setup to crash due to the Chrome binary not being found.
WARN: Selenium::WebDriver::Error::UnknownError: unknown error: cannot find Chrome binary (Driver info: chromedriver=2.40.565383 (76257d1ab79276b2d53ee976b2c3e3b9f335cde7),platform=Linux 4.4.0-1019-aws x86_64)
I am using the two relevant buildpacks on the Heroku-14 Stack
https://github.com/heroku/heroku-buildpack-xvfb-google-chrome
https://github.com/heroku/heroku-buildpack-chromedriver
Used gems:
gem 'selenium-webdriver','>=3.6.0'
gem 'chromedriver-helper'
I've spent the weekend trying to get this to work by passing various paths directly into the capybara.rb initializer (and compared these by running heroku run bash), but could not get it working.
capybara.rb
require "selenium/webdriver"
chrome_bin = ENV.fetch('GOOGLE_CHROME_SHIM', nil)
chrome_opts = chrome_bin ? { "chromeOptions" => { "binary" => 'app/.apt/usr/bin/google-chrome-stable' } } : {}
puts chrome_opts.to_s
Capybara.register_driver :chrome do |app|
Capybara::Selenium::Driver.new(
app,
browser: :chrome,
desired_capabilities: Selenium::WebDriver::Remote::Capabilities.chrome(chrome_opts)
)
end
Capybara.default_driver = :chrome
Capybara.javascript_driver = :chrome
I have also set the ENV vars in Heroku via the interface but when checking with ENV via heroku run rails c, it seems that the BIN var is loaded from the buildpack, and overrides my configuration.
I set GOOGLE_CHROME_BIN and GOOGLE_CHROME_SHIM to: /app/.apt/usr/bin/google-chrome
I'm no sure what kind of changes I have to make to get it working again. There are quite a few puzzle pieces, which one do I need to fix? Suggestions welcome!
SOLVED:
require "selenium/webdriver"
chrome_bin = ENV.fetch('GOOGLE_CHROME_SHIM', nil)
Capybara.register_driver :chrome do |app|
browser_options = ::Selenium::WebDriver::Chrome::Options.new
browser_options.binary = chrome_bin
Capybara::Selenium::Driver.new(app, browser: :chrome, options: browser_options)
end
Capybara.default_driver = :chrome
Capybara.javascript_driver = :chrome
I'm guessing you upgraded to the latest selenium-webdriver and chromedriver in the last few weeks. chromeOptions is no longer a valid key to pass, you can try changing it to goog:chromeOptions but you really should just be using an instance of the Selenium::WebDriver::Chrome::Options class
Capybara.register_driver :chrome do |app|
options = ::Selenium::WebDriver::Chrome::Options.new
options.binary = ...
Capybara::Selenium::Driver.new(app, browser: :chrome, options: browser_options)
end

ruby cucumber tests on multiple browsers

I am using windows 10 32 bit ruby version 233, I am facing these issues with running the tests on a ie 11 browser and the chrome browser for the tests(using page object) that are already running on firefox browser,
ISSUE with IE: Watir::Exception::NoMatchingWindowFoundException:
browser window was closed (eval):1:in `process_watir_call'
ISSUE with Chrome: Errno::ECONNREFUSED: Failed to open TCP connection
to 127.0.0.1:9515 (No connection could be made because the target
machine actively refused it. - connect(2) for "127.0.0.1" port 9515)
i have used the following hooks for ie and chrome:
Before do
case $browser
when 'mozilla'
#browser = Watir::Browser.new :firefox
#browser.window.maximize
when 'chrome'
#browser = Watir::Browser.new :chrome, :profile => "default"
when 'ie'
#browser = Watir::Browser.new :ie
# #browser.window.maximize
# #browser.visible = true
else
#browser = Watir::Browser.new :firefox
#browser.window.maximize
end
# #browser = Watir::Browser.new :firefox
# #browser.window.maximize
# this file contains test data that needs to be changed if tests are being executed in a different environment
$test_data = YAML.load_file('features/support/input_data/data/login_information.yml')
# this file contains base URL that needs to be changed if tests are being executed in a different environment
FigNewton.load('default.yml')
end
I was able to run a small sample test on a separate project from ruby mine with Watir gem.
Is there any way to make it work on the existing firefox tests?
The problem with chrome has been fixed by using the right chromedriver version, but still having problems with the IE using watir.
Found the solution for IE too its something to do with the internet options security and lower down the security level and uncheck the Enable Protected Mode.

how to download file to a specific location on .click of watir?

when I click on a link of a web page in chrome web browser with ruby watir
ie.input(:id, "c_ImageButton_Text").click
.text file start downloading. I want to download it to a specific location.I tried this code,but still getting.text file in default download location.How can I download .text file to specific location?
download_directory = "#{Dir.pwd}/downloads"
download_directory.gsub!("/", "\\") if Selenium::WebDriver::Platform.windows?
profile = Selenium::WebDriver::Chrome::Profile.new
profile['download.prompt_for_download'] = false
profile['download.default_directory'] = download_directory
b = Watir::Browser.new :chrome, :profile => profile
click here for this code
For latest watir version 6.6.1
prefs = {
prompt_for_download: false,
default_directory: Rails.root.join('tmp').to_s
}
options = Selenium::WebDriver::Chrome::Options.new
options.add_preference(:download, prefs)
browser = Watir::Browser.new :chrome, options: options
As the old saying goes, "There is more than one way to skin a cat":
You can certainly try to skin it the way you are attempting to do in your example code. However, there are a number of issues with this course of action. Namely, it is browser specific.
I really like how Elemental Selenium suggests achieving valid tests and assertions on downloading files by using the rest-client gem to curl the file's URI and assert the expectations of the file from from there: http://elemental-selenium.com/tips/8-download-a-file-revisited

Watir Webdriver Load Chrome Extension

I'm trying to load a chrome extension with Watir, and I'm having issues.
I found this related question: Ability to launch chrome with extensions loaded with watir-webdriver. However, I am still having the same issue after following that.
require 'rubygems'
require 'watir-webdriver'
require 'ruby-debug'
require 'nokogiri'
browser = Watir::Browser.new :chrome, :switches => %w[--load-extension=~/.config/google-chrome/Default/Extensions/anepbdekljkmmimmhbniglnnanmmkoja/0.1.12_0]
sleep(10)
browser.close
I also tried copying the extension from /Extensions to /Desktop and loading from there to no avail.
The error I get is Could not load extension from ... Manifest File Missing or Unreadable.
The Manifest file does indeed exist and seems to be a correct file in JSON format.
Trying to load different extensions fails as well.
Download the chrome extension crx file,
Store the args or any other option need to pass in the watir_opts hash
watir_opts[:extensions] = ['path of *.crx file']
browser = Watir::Browser.new :chrome, options: watir_opts
This worked for me.
Note: I didn't encode using 'base64' gem
If you pack the extension and then base64 it, you can load it into the Chrome browser right from your ruby code.
Pack your extension into a *.crx file. You can follow this guide, or just google how to pack a chrome extension.
Base64 it then add it to your desired capabilities list. You could use some code similar to this one:
chrome_extensions = []
chrome_extension_path = '\home\user\packed_chrome_extension.crx'
begin
File.open(chrome_extension_path, "rb") do |file|
chrome_extensions << Base64.encode64(file.read.chomp)
end
rescue Exception => e
raise "ERROR: Couldn't File.read or Base64.encode64 a Chrome extension: #{e.message}"
end
# Append the extensions to your capabilities hash
my_capabilities.merge!({'chrome.extensions' => chrome_extensions})
desired_capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(my_capabilities)
browser = Watir::Browser.new(:remote, :url => 'http://localhost:4444/wd/hub' :desired_capabilities => desired_capabilities)
And don't forget to require 'base64' too.
The example is for a remote web-driver instance, but I think it should work when using web-driver locally too. Just adjust the arguments passed to Watir::Browser.new.

Watir Changing Mozilla Firefox Preferences

I'm running a Ruby script using Watir to automate some things for me. I'm attempting to automatically save some files to a certain directory. So, in my Mozilla settings I set my default download directory to say the desktop and choose to automatically save files.
These changes, however, are not reflected when I begin to run my script. It seems like the preferences revert back to default. I've included the following
require "rubygems" # Optional.
require "watir-webdriver" # For web automation.
require "win32ole" # For file save dialog.
and open a new firefox instance with:
browser = Watir::Browser.new(:firefox)
Any ideas on why the preferences would be set back by this? Or any alternative ideas for what I am trying to do? (Automatically save files).
Thanks
WebDriver uses a clean profile for each browser instance, which is why the preferences appear to be "reset". You can tell it to use your default profile:
Watir::Browser.new :firefox, :profile => "default"
or tweak profile preferences programatically before launching the browser:
profile = Selenium::WebDriver::Firefox::Profile.new
profile['some.preference'] = true
profile.add_extension "/path/to/some/extension.xpi"
Watir::Browser.new :firefox, :profile => profile
For an example of configuring automatic file downloads, see this section on the Selenium wiki.
change default Watir preferences for download location
for chrome
profile = Selenium::WebDriver::Chrome::Profile.new
download_dir = File.join(Rails.root, 'lib', 'assets')
profile['download.default_directory'] = download_dir
profile[download.prompt_for_download] = false
#b = Watir::Browser.new :chrome, :profile => profile
for firefox
profile = Selenium::WebDriver::Firefox::Profile.new
download_dir = File.join(Rails.root, 'lib', 'assets')
profile['browser.download.dir'] = download_dir
profile['browser.helperApps.neverAsk.saveToDisk'] = "text/csv,application/pdf"
#b = Watir::Browser.new. :firefox, :profile => profile
note: to be be able to access the Rails.root/lib folder easily from within your rails app, you'll need to add this code or something like it to your config/application.rb file:
config.autoload_paths += Dir["#{config.root}/lib/**/"]
for more information: http://watirwebdriver.com/browser-downloads/

Resources