How to use clear method of Selenium.WebDriver Package

Best Selenium code snippet using Selenium.WebDriver.clear

driver.rb

Source:driver.rb Github

copy

Full Screen

...4class Capybara::Selenium::Driver < Capybara::Driver::Base5 include Capybara::Selenium::Find6 DEFAULT_OPTIONS = {7 browser: :firefox,8 clear_local_storage: nil,9 clear_session_storage: nil10 }.freeze11 SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze12 CAPS_VERSION = Gem::Requirement.new('~> 4.0.0.alpha6')13 attr_reader :app, :options14 class << self15 attr_reader :selenium_webdriver_version16 def load_selenium17 require 'selenium-webdriver'18 require 'capybara/selenium/logger_suppressor'19 require 'capybara/selenium/patches/atoms'20 require 'capybara/selenium/patches/is_displayed'21 require 'capybara/selenium/patches/action_pauser'22 # Look up the version of `selenium-webdriver` to23 # see if it's a version we support.24 #25 # By default, we use Gem.loaded_specs to determine26 # the version number. However, in some cases, such27 # as when loading `selenium-webdriver` outside of28 # Rubygems, we fall back to referencing29 # Selenium::WebDriver::VERSION. Ideally we'd30 # use the constant in all cases, but earlier versions31 # of `selenium-webdriver` didn't provide the constant.32 @selenium_webdriver_version =33 if Gem.loaded_specs['selenium-webdriver']34 Gem.loaded_specs['selenium-webdriver'].version35 else36 Gem::Version.new(Selenium::WebDriver::VERSION)37 end38 unless Gem::Requirement.new('>= 3.5.0').satisfied_by? @selenium_webdriver_version39 warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade."40 end41 @selenium_webdriver_version42 rescue LoadError => e43 raise e unless e.message.include?('selenium-webdriver')44 raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler."45 end46 attr_reader :specializations47 def register_specialization(browser_name, specialization)48 @specializations ||= {}49 @specializations[browser_name] = specialization50 end51 end52 def browser53 unless @browser54 options[:http_client] ||= begin55 require 'capybara/selenium/patches/persistent_client'56 if options[:timeout]57 ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout])58 else59 ::Capybara::Selenium::PersistentClient.new60 end61 end62 processed_options = options.reject { |key, _val| SPECIAL_OPTIONS.include?(key) }63 @browser = if options[:browser] == :firefox &&64 RUBY_VERSION >= '3.0' &&65 Capybara::Selenium::Driver.selenium_webdriver_version <= Gem::Version.new('4.0.0.alpha1')66 # selenium-webdriver 3.x doesn't correctly pass options through for Firefox with Ruby 3 so workaround that67 Selenium::WebDriver::Firefox::Driver.new(**processed_options)68 else69 Selenium::WebDriver.for(options[:browser], processed_options)70 end71 specialize_driver72 setup_exit_handler73 end74 @browser75 end76 def initialize(app, **options)77 super()78 self.class.load_selenium79 @app = app80 @browser = nil81 @exit_status = nil82 @frame_handles = Hash.new { |hash, handle| hash[handle] = [] }83 @options = DEFAULT_OPTIONS.merge(options)84 @node_class = ::Capybara::Selenium::Node85 end86 def visit(path)87 browser.navigate.to(path)88 end89 def refresh90 browser.navigate.refresh91 end92 def go_back93 browser.navigate.back94 end95 def go_forward96 browser.navigate.forward97 end98 def html99 browser.page_source100 rescue Selenium::WebDriver::Error::JavascriptError => e101 raise unless e.message.include?('documentElement is null')102 end103 def title104 browser.title105 end106 def current_url107 browser.current_url108 end109 def wait?; true; end110 def needs_server?; true; end111 def execute_script(script, *args)112 browser.execute_script(script, *native_args(args))113 end114 def evaluate_script(script, *args)115 result = execute_script("return #{script}", *args)116 unwrap_script_result(result)117 end118 def evaluate_async_script(script, *args)119 browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time120 result = browser.execute_async_script(script, *native_args(args))121 unwrap_script_result(result)122 end123 def send_keys(*args)124 active_element.send_keys(*args)125 end126 def save_screenshot(path, **_options)127 browser.save_screenshot(path)128 end129 def reset!130 # Use instance variable directly so we avoid starting the browser just to reset the session131 return unless @browser132 navigated = false133 timer = Capybara::Helpers.timer(expire_in: 10)134 begin135 # Only trigger a navigation if we haven't done it already, otherwise it136 # can trigger an endless series of unload modals137 reset_browser_state unless navigated138 navigated = true139 # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload140 wait_for_empty_page(timer)141 rescue *unhandled_alert_errors142 # This error is thrown if an unhandled alert is on the page143 # Firefox appears to automatically dismiss this alert, chrome does not144 # We'll try to accept it145 accept_unhandled_reset_alert146 # try cleaning up the browser again147 retry148 end149 end150 def frame_obscured_at?(x:, y:)151 frame = @frame_handles[current_window_handle].last152 return false unless frame153 switch_to_frame(:parent)154 begin155 frame.base.obscured?(x: x, y: y)156 ensure157 switch_to_frame(frame)158 end159 end160 def switch_to_frame(frame)161 handles = @frame_handles[current_window_handle]162 case frame163 when :top164 handles.clear165 browser.switch_to.default_content166 when :parent167 handles.pop168 browser.switch_to.parent_frame169 else170 handles << frame171 browser.switch_to.frame(frame.native)172 end173 end174 def current_window_handle175 browser.window_handle176 end177 def window_size(handle)178 within_given_window(handle) do179 size = browser.manage.window.size180 [size.width, size.height]181 end182 end183 def resize_window_to(handle, width, height)184 within_given_window(handle) do185 browser.manage.window.resize_to(width, height)186 end187 end188 def maximize_window(handle)189 within_given_window(handle) do190 browser.manage.window.maximize191 end192 sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405193 end194 def fullscreen_window(handle)195 within_given_window(handle) do196 browser.manage.window.full_screen197 end198 end199 def close_window(handle)200 raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first201 within_given_window(handle) do202 browser.close203 end204 end205 def window_handles206 browser.window_handles207 end208 def open_new_window(kind = :tab)209 browser.manage.new_window(kind)210 rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError211 # If not supported by the driver or browser default to using JS212 browser.execute_script('window.open();')213 end214 def switch_to_window(handle)215 browser.switch_to.window handle216 end217 def accept_modal(_type, **options)218 yield if block_given?219 modal = find_modal(**options)220 modal.send_keys options[:with] if options[:with]221 message = modal.text222 modal.accept223 message224 end225 def dismiss_modal(_type, **options)226 yield if block_given?227 modal = find_modal(**options)228 message = modal.text229 modal.dismiss230 message231 end232 def quit233 @browser&.quit234 rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED,235 Selenium::WebDriver::Error::InvalidSessionIdError236 # Browser must have already gone237 rescue Selenium::WebDriver::Error::UnknownError => e238 unless silenced_unknown_error_message?(e.message) # Most likely already gone239 # probably already gone but not sure - so warn240 warn "Ignoring Selenium UnknownError during driver quit: #{e.message}"241 end242 ensure243 @browser = nil244 end245 def invalid_element_errors246 @invalid_element_errors ||= begin247 [248 ::Selenium::WebDriver::Error::StaleElementReferenceError,249 ::Selenium::WebDriver::Error::ElementNotInteractableError,250 ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition251 ::Selenium::WebDriver::Error::ElementClickInterceptedError,252 ::Selenium::WebDriver::Error::NoSuchElementError, # IE253 ::Selenium::WebDriver::Error::InvalidArgumentError # IE254 ].tap do |errors|255 unless selenium_4?256 ::Selenium::WebDriver.logger.suppress_deprecations do257 errors.concat [258 ::Selenium::WebDriver::Error::UnhandledError,259 ::Selenium::WebDriver::Error::ElementNotVisibleError,260 ::Selenium::WebDriver::Error::InvalidElementStateError,261 ::Selenium::WebDriver::Error::ElementNotSelectableError262 ]263 end264 end265 end266 end267 end268 def no_such_window_error269 Selenium::WebDriver::Error::NoSuchWindowError270 end271private272 def selenium_4?273 defined?(Selenium::WebDriver::VERSION) && (Selenium::WebDriver::VERSION.to_f >= 4)274 end275 def native_args(args)276 args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg }277 end278 def clear_browser_state279 delete_all_cookies280 clear_storage281 rescue *clear_browser_state_errors282 # delete_all_cookies fails when we've previously gone283 # to about:blank, so we rescue this error and do nothing284 # instead.285 end286 def clear_browser_state_errors287 @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError]288 end289 def unhandled_alert_errors290 @unhandled_alert_errors ||= with_legacy_error(291 [Selenium::WebDriver::Error::UnexpectedAlertOpenError],292 'UnhandledAlertError'293 )294 end295 def delete_all_cookies296 @browser.manage.delete_all_cookies297 end298 def clear_storage299 clear_session_storage unless options[:clear_session_storage] == false300 clear_local_storage unless options[:clear_local_storage] == false301 rescue Selenium::WebDriver::Error::JavascriptError302 # session/local storage may not be available if on non-http pages (e.g. about:blank)303 end304 def clear_session_storage305 if @browser.respond_to? :session_storage306 @browser.session_storage.clear307 else308 begin309 @browser&.execute_script('window.sessionStorage.clear()')310 rescue # rubocop:disable Style/RescueStandardError311 unless options[:clear_session_storage].nil?312 warn 'sessionStorage clear requested but is not supported by this driver'313 end314 end315 end316 end317 def clear_local_storage318 if @browser.respond_to? :local_storage319 @browser.local_storage.clear320 else321 begin322 @browser&.execute_script('window.localStorage.clear()')323 rescue # rubocop:disable Style/RescueStandardError324 unless options[:clear_local_storage].nil?325 warn 'localStorage clear requested but is not supported by this driver'326 end327 end328 end329 end330 def navigate_with_accept(url)331 @browser.navigate.to(url)332 sleep 0.1 # slight wait for alert333 @browser.switch_to.alert.accept334 rescue modal_error335 # alert now gone, should mean navigation happened336 end337 def modal_error338 Selenium::WebDriver::Error::NoSuchAlertError339 end340 def within_given_window(handle)341 original_handle = current_window_handle342 if handle == original_handle343 yield344 else345 switch_to_window(handle)346 result = yield347 switch_to_window(original_handle)348 result349 end350 end351 def find_modal(text: nil, **options)352 # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time353 # Actual wait time may be longer than specified354 wait = Selenium::WebDriver::Wait.new(355 timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0,356 ignore: modal_error357 )358 begin359 wait.until do360 alert = @browser.switch_to.alert361 regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s))362 matched = alert.text.match?(regexp)363 unless matched364 raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead."365 end366 alert367 end368 rescue *find_modal_errors369 raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}"370 end371 end372 def find_modal_errors373 @find_modal_errors ||= with_legacy_error([Selenium::WebDriver::Error::TimeoutError], 'TimeOutError')374 end375 def with_legacy_error(errors, legacy_error)376 errors.tap do |errs|377 unless selenium_4?378 ::Selenium::WebDriver.logger.suppress_deprecations do379 errs << Selenium::WebDriver::Error.const_get(legacy_error)380 end381 end382 end383 end384 def silenced_unknown_error_message?(msg)385 silenced_unknown_error_messages.any? { |regex| msg.match? regex }386 end387 def silenced_unknown_error_messages388 [/Error communicating with the remote browser/]389 end390 def unwrap_script_result(arg)391 case arg392 when Array393 arg.map { |arr| unwrap_script_result(arr) }394 when Hash395 arg.transform_values! { |value| unwrap_script_result(value) }396 when Selenium::WebDriver::Element397 build_node(arg)398 else399 arg400 end401 end402 def find_context403 browser404 end405 def active_element406 browser.switch_to.active_element407 end408 def build_node(native_node, initial_cache = {})409 ::Capybara::Selenium::Node.new(self, native_node, initial_cache)410 end411 def bridge412 browser.send(:bridge)413 end414 def specialize_driver415 browser_type = browser.browser416 Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality417 extend specialization418 end419 end420 def setup_exit_handler421 main = Process.pid422 at_exit do423 # Store the exit status of the test run since it goes away after calling the at_exit proc...424 @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit)425 quit if Process.pid == main426 exit @exit_status if @exit_status # Force exit with stored status427 end428 end429 def reset_browser_state430 clear_browser_state431 @browser.navigate.to('about:blank')432 end433 def wait_for_empty_page(timer)434 until find_xpath('/html/body/*').empty?435 raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired?436 sleep 0.01437 # It has been observed that it is possible that asynchronous JS code in438 # the application under test can navigate the browser away from about:blank439 # if the timing is just right. Ensure we are still at about:blank...440 @browser.navigate.to('about:blank') unless current_url == 'about:blank'441 end442 end443 def accept_unhandled_reset_alert444 @browser.switch_to.alert.accept...

Full Screen

Full Screen

clear

Using AI Code Generation

copy

Full Screen

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').clear6driver.find_element(:name, 'q').send_keys "Selenium WebDriver"7driver.find_element(:name, 'btnG').click8puts driver.find_element(:name, 'q').get

Full Screen

Full Screen

clear

Using AI Code Generation

copy

Full Screen

1driver.find_element(:name, 'q').send_keys "selenium"2driver.find_element(:name, 'q').clear3driver.find_element(:name, 'q').send_keys "webdriver"4driver.find_element(:name, 'btnG').click

Full Screen

Full Screen

clear

Using AI Code Generation

copy

Full Screen

1driver.manage().window().maximize()2driver.find_element(:name, 'q').send_keys "Selenium"3driver.find_element(:name, 'btnG').click4driver.find_element(:link_text, 'Selenium - Web Browser Automation').click

Full Screen

Full Screen

clear

Using AI Code Generation

copy

Full Screen

1driver.manage.window.resize_to(500, 500)2driver.manage.window.move_to(100, 100)3driver.manage.window.resize_to(500, 500)4driver.manage.window.move_to(100, 100)5driver.manage.window.resize_to(500, 500)6driver.manage.window.move_to(100, 100)7driver.manage.window.resize_to(500, 500)8driver.manage.window.move_to(100, 100)9driver.manage.window.resize_to(500, 500)10driver.manage.window.move_to(100, 100)11driver.manage.window.resize_to(500, 500)12driver.manage.window.move_to(100, 100)13driver.manage.window.resize_to(500, 500)14driver.manage.window.move_to(100, 100)15driver.manage.window.resize_to(500, 500)16driver.manage.window.move_to(100, 100)17driver.manage.window.resize_to(500, 500)18driver.manage.window.move_to(100, 100)19driver.manage.window.resize_to(500, 500)20driver.manage.window.move_to(100, 100)

Full Screen

Full Screen

clear

Using AI Code Generation

copy

Full Screen

1element = driver.find_element(:name, 'q')2element = driver.find_element(:name, 'q')3element = driver.find_element(:name, 'q')

Full Screen

Full Screen

clear

Using AI Code Generation

copy

Full Screen

1driver.manage().window().maximize()2driver.manage().delete_all_cookies()3driver.quit()4driver.manage.delete_cookie(name)5driver.manage().window().maximize()6driver.manage().delete_cookie("NID")7driver.quit()8driver.manage().window().maximize()9driver.manage().delete_all_cookies()10driver.quit()

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful