Best Selenium code snippet using Selenium.WebDriver.device
options.rb
Source:options.rb
...110 def add_preference(name, value)111 prefs[name] = value112 end113 #114 # Add an emulation device name115 #116 # @example Start Chrome in mobile emulation mode by device name117 # options = Selenium::WebDriver::Chrome::Options.new118 # options.add_emulated_device(device_name: 'iPhone 6')119 #120 # @example Start Chrome in mobile emulation mode by device metrics121 # options = Selenium::WebDriver::Chrome::Options.new122 # options.add_emulated_device(device_metrics: {width: 400, height: 800, pixelRatio: 1, touch: true})123 #124 # @param [String] device_name Name of the device or a hash containing width, height, pixelRatio, touch125 # @param [Hash] device_metrics Hash containing width, height, pixelRatio, touch126 # @param [String] user_agent Full user agent127 #128 def add_emulation(device_name: nil, device_metrics: nil, user_agent: nil)129 @emulation[:deviceName] = device_name if device_name130 @emulation[:deviceMetrics] = device_metrics if device_metrics131 @emulation[:userAgent] = user_agent if user_agent132 end133 #134 # @api private135 #136 def as_json(*)137 extensions = @extensions.map do |crx_path|138 File.open(crx_path, 'rb') { |crx_file| Base64.strict_encode64 crx_file.read }139 end140 extensions.concat(@encoded_extensions)141 opts = @options142 opts[:binary] = @binary if @binary143 opts[:args] = @args if @args.any?144 opts[:extensions] = extensions if extensions.any?...
platform.rb
Source:platform.rb
...71 end72 def cygwin?73 !!(RUBY_PLATFORM =~ /cygwin/)74 end75 def null_device76 @null_device ||= (77 if defined?(File::NULL)78 File::NULL79 else80 Platform.windows? ? 'NUL' : '/dev/null'81 end82 )83 end84 def wrap_in_quotes_if_necessary(str)85 windows? && !cygwin? ? %{"#{str}"} : str86 end87 def cygwin_path(path, opts = {})88 flags = []89 opts.each { |k,v| flags << "--#{k}" if v }90 `cygpath #{flags.join ' '} "#{path}"`.strip91 end92 def make_writable(file)93 File.chmod 0766, file94 end95 def assert_file(path)96 unless File.file? path97 raise Error::WebDriverError, "not a file: #{path.inspect}"98 end99 end100 def assert_executable(path)101 assert_file(path)102 unless File.executable? path103 raise Error::WebDriverError, "not executable: #{path.inspect}"104 end105 end106 def exit_hook(&blk)107 pid = Process.pid108 at_exit do109 yield if Process.pid == pid110 end111 end112 def find_binary(*binary_names)113 paths = ENV['PATH'].split(File::PATH_SEPARATOR)114 binary_names.map! { |n| "#{n}.exe" } if windows?115 binary_names.each do |binary_name|116 paths.each do |path|117 exe = File.join(path, binary_name)118 return exe if File.executable?(exe)119 end120 end121 nil122 end123 def find_in_program_files(*binary_names)124 paths = [125 ENV['PROGRAMFILES'] || "\\Program Files",126 ENV['ProgramFiles(x86)'] || "\\Program Files (x86)"127 ]128 paths.each do |root|129 binary_names.each do |name|130 exe = File.join(root, name)131 return exe if File.executable?(exe)132 end133 end134 nil135 end136 def localhost137 info = Socket.getaddrinfo "localhost", 80, Socket::AF_INET, Socket::SOCK_STREAM138 if info.empty?139 raise Error::WebDriverError, "unable to translate 'localhost' for TCP + IPv4"140 end141 info[0][3]142 end143 def ip144 orig = Socket.do_not_reverse_lookup145 Socket.do_not_reverse_lookup = true146 begin147 UDPSocket.open do |s|148 s.connect '8.8.8.8', 53149 return s.addr.last150 end151 ensure152 Socket.do_not_reverse_lookup = orig153 end154 rescue Errno::ENETUNREACH, Errno::EHOSTUNREACH155 # no external ip156 end157 def interfaces158 interfaces = Socket.getaddrinfo("localhost", 8080).map { |e| e[3] }159 interfaces += ["0.0.0.0", Platform.ip]160 interfaces.compact.uniq161 end162 end # Platform163 end # WebDriver164end # Selenium165if __FILE__ == $0166 p :engine => Selenium::WebDriver::Platform.engine,167 :os => Selenium::WebDriver::Platform.os,168 :ruby187? => Selenium::WebDriver::Platform.ruby187?,169 :ruby19? => Selenium::WebDriver::Platform.ruby19?,170 :jruby? => Selenium::WebDriver::Platform.jruby?,171 :windows? => Selenium::WebDriver::Platform.windows?,172 :home => Selenium::WebDriver::Platform.home,173 :bitsize => Selenium::WebDriver::Platform.bitsize,174 :localhost => Selenium::WebDriver::Platform.localhost,175 :ip => Selenium::WebDriver::Platform.ip,176 :interfaces => Selenium::WebDriver::Platform.interfaces,177 :null_device => Selenium::WebDriver::Platform.null_device178end...
driver_config.rb
Source:driver_config.rb
...36 @driver.manage.timeouts.page_load = 12037 @driver.manage.window.maximize38end39#Device40def launch_driver_device41 #puts "Launching driver for chrome.........................."42 # @driver = Selenium::WebDriver.for :chrome43 # @driver.manage.timeouts.implicit_wait = 6044 # @driver.manage.window.maximize45 deviceName = ENV['VERSION']46 deviceName = deviceName.gsub("_", " ")47 mobile_emulation = { "deviceName" => deviceName }48 caps = Selenium::WebDriver::Remote::Capabilities.chrome(49 "chromeOptions" => { "mobileEmulation" => mobile_emulation })50 @driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps51 @driver.manage.timeouts.implicit_wait = 6052end53#IE browser54def launch_driver_ie55 client = Selenium::WebDriver::Remote::Http::Default.new56 client.timeout = 12057 caps = Selenium::WebDriver::Remote::Capabilities.ie('ie.ensureCleanSession' => true, :javascript_enabled => true, :native_events => false, :acceptSslCerts => true)58 @driver = Selenium::WebDriver.for(:remote, :http_client => client, :url => "http://localhost:5555", :desired_capabilities => caps)59 @driver.manage.timeouts.implicit_wait = 9060 @driver.manage.timeouts.page_load = 12061 @driver.manage.window.size = Selenium::WebDriver::Dimension.new(1366,768)...
webdriver_handler_spec.rb
Source:webdriver_handler_spec.rb
...12 allow(Bucky::Utils::Config).to receive(:instance).and_return(config_double)13 allow(config_double).to receive('[]').with(:browser).and_return(browser)14 allow(config_double).to receive('[]').with(:selenium_ip).and_return(selenium_ip)15 allow(config_double).to receive('[]').with(:selenium_port).and_return(selenium_port)16 allow(config_double).to receive('[]').with(:device_name_on_chrome).and_return(device_name_on_chrome)17 allow(config_double).to receive('[]').with(:sp_device_name).and_return(sp_device_name)18 allow(config_double).to receive('[]').with(:tablet_device_name).and_return(sp_device_name)19 allow(config_double).to receive('[]').with(:bucky_error).and_return(bucky_error)20 allow(config_double).to receive('[]').with(:driver_open_timeout).and_return(10)21 allow(config_double).to receive('[]').with(:driver_read_timeout).and_return(10)22 allow(config_double).to receive('[]').with(:user_agent).and_return(10)23 allow(config_double).to receive('[]').with(:find_element_timeout).and_return(10)24 allow(config_double).to receive('[]').with(:headless).and_return(headless)25 allow(config_double).to receive('[]').with(:chromedriver_flags).and_return(chromedriver_flags)26 allow(Selenium::WebDriver).to receive(:for).and_return(webdriver_double)27 allow(webdriver_double).to receive(:manage).and_return(webdriver_manage_double)28 allow(webdriver_manage_double).to receive(:window).and_return(webdriver_manage_window_double)29 allow(webdriver_manage_window_double).to receive(:resize_to)30 allow(webdriver_manage_double).to receive(:timeouts).and_return(webdriver_manage_timeouts_double)31 allow(webdriver_manage_timeouts_double).to receive(:implicit_wait=)32 end33 describe '#create_webdriver' do34 let(:selenium_ip) { '11.22.33.44' }35 let(:selenium_port) { '4444' }36 let(:device_name_on_chrome) { { iphone6: 'Apple iPhone 6' } }37 let(:sp_device_name) { :iphone6 }38 let(:sp_device_name) { :ipad }39 let(:bucky_error) { 'bucky error' }40 let(:headless) { false }41 let(:chromedriver_flags) { ['--foo', '--bar', '--baz'] }42 context 'pc' do43 let(:device_type) { 'pc' }44 context 'browser is chrome' do45 let(:browser) { :chrome }46 it 'call Selenium::WebDriver.for' do47 expect(Selenium::WebDriver).to receive(:for)48 create_webdriver(device_type)49 end50 end51 context 'browser is not chrome' do52 let(:browser) { :firefox }53 it 'raise exception' do54 expect(Bucky::Core::Exception::BuckyException).to receive(:handle)55 create_webdriver(device_type)56 end57 end58 end59 context 'sp' do60 let(:device_type) { 'sp' }61 context 'browser is chrome' do62 let(:browser) { :chrome }63 it 'call Selenium::WebDriver.for' do64 expect(Selenium::WebDriver).to receive(:for)65 create_webdriver(device_type)66 end67 end68 context 'browser is not chrome' do69 let(:browser) { :firefox }70 let(:selenium_mode) { :remote }71 it 'raise exception' do72 expect(Bucky::Core::Exception::BuckyException).to receive(:handle)73 create_webdriver(device_type)74 end75 end76 end77 context 'tablet' do78 let(:device_type) { 'tablet' }79 context 'browser is chrome' do80 let(:browser) { :chrome }81 it 'call Selenium::WebDriver.for' do82 expect(Selenium::WebDriver).to receive(:for)83 create_webdriver(device_type)84 end85 end86 context 'browser is not chrome' do87 let(:browser) { :firefox }88 let(:selenium_mode) { :remote }89 it 'raise exception' do90 expect(Bucky::Core::Exception::BuckyException).to receive(:handle)91 create_webdriver(device_type)92 end93 end94 end95 end96end...
sharedWebDriver.rb
Source:sharedWebDriver.rb
...11 case tconfigObj["MODE"]12 when "ui"13 Selenium::WebDriver::Chrome.driver_path=tconfigObj["DRIVER_PATH"]14 options = Selenium::WebDriver::Chrome::Options.new15 options = enable_mobile_device(options, tconfigObj)16 options.add_argument('start-maximized')17 @driver = Selenium::WebDriver.for(:chrome, options: options)18 when "headless-chrome"19 Selenium::WebDriver::Chrome.driver_path=tconfigObj["DRIVER_PATH"]20 options = Selenium::WebDriver::Chrome::Options.new21 options.add_argument('--headless')22 options = enable_mobile_device(options, tconfigObj)23 options.add_argument('start-maximized')24 @driver = Selenium::WebDriver.for(:chrome, options: options)25 when "headless-cancary"26 Selenium::WebDriver::Chrome.driver_path=tconfigObj["DRIVER_PATH"]27 caps = Selenium::WebDriver::Remote::Capabilities.chrome(chromeOptions: {28 binary: "/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary", 29 args: [ "--headless" ]})30 @driver = Selenium::WebDriver.for(:chrome, desired_capabilities: caps)31 when "browserstack"32 tconfigObjBrowserStack = load_config(Dir.pwd + "/configuration/user_browserstack.json")33 caps = Selenium::WebDriver::Remote::Capabilities.new34 caps["os"] = tconfigObjBrowserStack["BROWSERSTACK_OS"]35 caps["os_version"] = tconfigObjBrowserStack["BROWSERSTACK_OSVERSION"]36 caps["browser"] = tconfigObjBrowserStack["BROWSERSTACK_BROWSER"]37 caps["browser_version"] = tconfigObjBrowserStack["BROWSERSTACK_BROWSERVERSION"]38 caps["resolution"] = tconfigObjBrowserStack["BROWSERSTACK_RESOLUTION"]39 caps["browserstack.local"] = tconfigObjBrowserStack["BROWSERSTACK_LOCAL"]40 caps["browserstack.selenium_version"] = tconfigObjBrowserStack["BROWSERSTACK_SELENIUMVERSION"]41 remoteHunUrl = "http://%s:%s@hub-cloud.browserstack.com/wd/hub" % [tconfigObjBrowserStack["BROWSERSTACK_USERNAME"], tconfigObjBrowserStack["BROWSERSTACK_ACCESSKEY"]]42 @driver = Selenium::WebDriver.for(:remote, :url => remoteHunUrl, :desired_capabilities => caps)43 when "hub"44 tconfigObjHub = load_config(Dir.pwd + "/configuration/user_hub.json")45 caps = Selenium::WebDriver::Remote::Capabilities.new46 caps["browserName"] = tconfigObjHub["NODE_BROWSER_NAME"]47 caps["browserVersion"] = tconfigObjHub["NODE_BROWSER_VERSION"]48 caps["platform"] = tconfigObjHub["NODE_PLATFORM"]49 caps["seleniumVersion"] = tconfigObjHub["NODE_SELENIUM_VERSION"]50 @driver = Selenium::WebDriver.for(:remote, :url => "%s/wd/hub" % [tconfigObjHub["HUB_URL"]], :desired_capabilities => caps)51 else52 Selenium::WebDriver::Chrome.driver_path=tconfigObj["DRIVER_PATH"]53 options = Selenium::WebDriver::Chrome::Options.new54 options = enable_mobile_device(options, tconfigObj)55 options.add_argument('start-maximized')56 @driver = Selenium::WebDriver.for(:chrome, options: options)57 end58 @driver.manage.window.move_to(0, 0)59 @wait = Selenium::WebDriver::Wait.new(:timeout => 30) # seconds60 @listWait = Selenium::WebDriver::Wait.new(:timeout => 120) # seconds61 @shortWait = Selenium::WebDriver::Wait.new(:timeout => 3) # seconds62 @normalWait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds63 end64 65 def get_driver()66 return @driver67 end68 69 def get_waitor()70 return @wait71 end72 73 def get_short_waitor()74 return @shortWait75 end7677 def get_normal_waitor()78 return @normalWait79 end8081 def get_list_waitor()82 return @listWait83 end8485 private def enable_mobile_device(options, tconfigObj)86 if tconfigObj["USER_AGENT"] != "" && tconfigObj["DEVICE_NAME"] != ""87 options.add_argument('user-agent=' + tconfigObj["USER_AGENT"])88 options.add_emulation(:device_name => tconfigObj["DEVICE_NAME"])89 end90 return options91 end9293end
...
common.rb
Source:common.rb
...58require 'selenium/webdriver/common/driver_extensions/has_remote_status'59require 'selenium/webdriver/common/driver_extensions/has_network_connection'60require 'selenium/webdriver/common/driver_extensions/uploads_files'61require 'selenium/webdriver/common/interactions/interactions'62require 'selenium/webdriver/common/interactions/input_device'63require 'selenium/webdriver/common/interactions/interaction'64require 'selenium/webdriver/common/interactions/none_input'65require 'selenium/webdriver/common/interactions/key_input'66require 'selenium/webdriver/common/interactions/pointer_input'67require 'selenium/webdriver/common/keys'68require 'selenium/webdriver/common/bridge_helper'69require 'selenium/webdriver/common/profile_helper'70require 'selenium/webdriver/common/driver'71require 'selenium/webdriver/common/element'...
device
Using AI Code Generation
1element = driver.find_element(:name, 'q')2element = driver.find_element(:name, 'q')3element = driver.find_element(:name, 'q')4element = driver.find_element(:name, 'q')5element = driver.find_element(:name, 'q')6element = driver.find_element(:name, 'q')
device
Using AI Code Generation
1driver.find_element(:name, "q").send_keys "Selenium WebDriver"2driver.find_element(:name, "btnG").click3driver.find_element(:name, "q").send_keys "Selenium WebDriver"4driver.find_element(:name, "btnG").click5driver.find_element(:name, "q").send_keys "Selenium WebDriver"6driver.find_element(:name, "btnG").click7driver.find_element(:name, "q").send_keys "Selenium WebDriver"8driver.find_element(:name, "btnG").click9driver.find_element(:name, "q").send_keys "Selenium WebDriver"10driver.find_element(:name, "btnG").click11driver.find_element(:name, "q").send_keys "Selenium WebDriver
device
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnK').click3Select Console App (.NET Framework)
device
Using AI Code Generation
1element = driver.find_element(:name, 'q')2element = driver.find_element(:name, 'q')3element = driver.find_element(:name, 'q')4element = driver.find_element(:name, 'q')5element = driver.find_element(:name, 'q')6element = driver.find_element(:name, 'q')
device
Using AI Code Generation
1element = driver.find_element(:name, 'q')2element = driver.find_element(:name, 'q')3element = driver.find_element(:name, 'q')4element = driver.find_element(:name, 'q')5element = driver.find_element(:name, 'q')6element = driver.find_element(:name, 'q')
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!