def __init__(self, driver, event_listener): """ Creates a new instance of the EventFiringWebDriver :Args: - driver : A WebDriver instance - event_listener : Instance of a class that subclasses AbstractEventListener and implements it fully or partially Example: .. code-block:: python from modules.selenium.webdriver import Firefox from modules.selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener class MyListener(AbstractEventListener): def before_navigate_to(self, url, driver): print("Before navigate to %s" % url) def after_navigate_to(self, url, driver): print("After navigate to %s" % url) driver = Firefox() ef_driver = EventFiringWebDriver(driver, MyListener()) ef_driver.get("http://www.google.co.in/") """ if not isinstance(driver, WebDriver): raise WebDriverException("A WebDriver instance must be supplied") if not isinstance(event_listener, AbstractEventListener): raise WebDriverException( "Event listener must be a subclass of AbstractEventListener") self._driver = driver self._driver._wrap_value = self._wrap_value self._listener = event_listener
def port(self, port): """ Sets the port that WebDriver will be running on """ if not isinstance(port, int): raise WebDriverException("Port needs to be an integer") try: port = int(port) if port < 1 or port > 65535: raise WebDriverException( "Port number must be in the range 1..65535") except (ValueError, TypeError): raise WebDriverException("Port needs to be an integer") self._port = port self.set_preference("webdriver_firefox_port", self._port)
def __init__(self, firefox_path=None, log_file=None): """ Creates a new instance of Firefox binary. :Args: - firefox_path - Path to the Firefox executable. By default, it will be detected from the standard locations. - log_file - A file object to redirect the firefox process output to. It can be sys.stdout. Please note that with parallel run the output won't be synchronous. By default, it will be redirected to /dev/null. """ self._start_cmd = firefox_path # We used to default to subprocess.PIPE instead of /dev/null, but after # a while the pipe would fill up and Firefox would freeze. self._log_file = log_file or open(os.devnull, "wb") self.command_line = None if self._start_cmd is None: self._start_cmd = self._get_firefox_start_cmd() if not self._start_cmd.strip(): raise WebDriverException( "Failed to find firefox binary. You can set it by specifying " "the path to 'firefox_binary':\n\nfrom " "selenium.webdriver.firefox.firefox_binary import " "FirefoxBinary\n\nbinary = " "FirefoxBinary('/path/to/binary')\ndriver = " "webdriver.Firefox(firefox_binary=binary)") # Rather than modifying the environment of the calling Python process # copy it and modify as needed. self._firefox_env = os.environ.copy() self._firefox_env["MOZ_CRASHREPORTER_DISABLE"] = "1" self._firefox_env["MOZ_NO_REMOTE"] = "1" self._firefox_env["NO_EM_RESTART"] = "1"
def start(self): """ Starts the Service. :Exceptions: - WebDriverException : Raised either when it can't start the service or when it can't connect to the service """ try: cmd = [self.path] cmd.extend(self.command_line_args()) self.process = subprocess.Popen( cmd, env=self.env, close_fds=platform.system() != 'Windows', stdout=self.log_file, stderr=self.log_file, stdin=PIPE) except TypeError: raise except OSError as err: if err.errno == errno.ENOENT: raise WebDriverException( "'%s' executable needs to be in PATH. %s" % (os.path.basename(self.path), self.start_error_message)) elif err.errno == errno.EACCES: raise WebDriverException( "'%s' executable may have wrong permissions. %s" % (os.path.basename(self.path), self.start_error_message)) else: raise except Exception as e: raise WebDriverException( "The executable %s needs to be available in the path. %s\n%s" % (os.path.basename( self.path), self.start_error_message, str(e))) count = 0 while True: self.assert_process_still_running() if self.is_connectable(): break count += 1 time.sleep(1) if count == 30: raise WebDriverException("Can not connect to the Service %s" % self.path)
def set_permission(self, permission, value): if not isinstance(value, bool): raise WebDriverException( "Value of a session permission must be set to True or False.") payload = {} payload[permission] = value self.execute("SET_PERMISSIONS", {"permissions": payload})
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False, file_detector=None, options=None): """ Create a new driver that will issue commands using the wire protocol. :Args: - command_executor - Either a string representing URL of the remote server or a custom remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'. - desired_capabilities - A dictionary of capabilities to request when starting the browser session. Required parameter. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested. Optional. - proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will be started with given proxy settings, if possible. Optional. - keep_alive - Whether to configure remote_connection.RemoteConnection to use HTTP keep-alive. Defaults to False. - file_detector - Pass custom file detector object during instantiation. If None, then default LocalFileDetector() will be used. - options - instance of a driver options.Options class """ capabilities = {} if options is not None: capabilities = options.to_capabilities() if desired_capabilities is not None: if not isinstance(desired_capabilities, dict): raise WebDriverException( "Desired Capabilities must be a dictionary") else: capabilities.update(desired_capabilities) if proxy is not None: warnings.warn("Please use FirefoxOptions to set proxy", DeprecationWarning, stacklevel=2) proxy.add_to_capabilities(capabilities) self.command_executor = command_executor if type(self.command_executor) is bytes or isinstance( self.command_executor, str): self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive) self._is_remote = True self.session_id = None self.capabilities = {} self.error_handler = ErrorHandler() self.start_client() if browser_profile is not None: warnings.warn("Please use FirefoxOptions to set browser profile", DeprecationWarning, stacklevel=2) self.start_session(capabilities, browser_profile) self._switch_to = SwitchTo(self) self._mobile = Mobile(self) self.file_detector = file_detector or LocalFileDetector()
def file_detector(self, detector): """ Set the file detector to be used when sending keyboard input. By default, this is set to a file detector that does nothing. see FileDetector see LocalFileDetector see UselessFileDetector :Args: - detector: The detector to use. Must not be None. """ if detector is None: raise WebDriverException( "You may not set a file detector that is null") if not isinstance(detector, FileDetector): raise WebDriverException( "Detector has to be instance of FileDetector") self._file_detector = detector
def _wait_until_connectable(self, timeout=30): """Blocks until the extension is connectable in the firefox.""" count = 0 while not utils.is_connectable(self.profile.port): if self.process.poll() is not None: # Browser has exited raise WebDriverException( "The browser appears to have exited " "before we could connect. If you specified a log_file in " "the FirefoxBinary constructor, check it for details.") if count >= timeout: self.kill() raise WebDriverException( "Can't load the profile. Possible firefox version mismatch. " "You must use GeckoDriver instead for Firefox 48+. Profile " "Dir: %s If you specified a log_file in the " "FirefoxBinary constructor, check it for details." % (self.profile.path)) count += 1 time.sleep(1) return True
def orientation(self, value): """ Sets the current orientation of the device :Args: - value: orientation to set it to. :Usage: driver.orientation = 'landscape' """ allowed_values = ['LANDSCAPE', 'PORTRAIT'] if value.upper() in allowed_values: self.execute(Command.SET_SCREEN_ORIENTATION, {'orientation': value}) else: raise WebDriverException( "You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'" )
def native_events_enabled(self, value): if value not in [True, False]: raise WebDriverException("Please pass in a Boolean to this call") self.set_preference("webdriver_enable_native_events", value)
def assume_untrusted_cert_issuer(self, value): if value not in [True, False]: raise WebDriverException("Please pass in a Boolean to this call") self.set_preference("webdriver_assume_untrusted_issuer", value)
def assert_process_still_running(self): return_code = self.process.poll() if return_code is not None: raise WebDriverException( 'Service %s unexpectedly exited. Status code was: %s' % (self.path, return_code))
def __init__(self, device_password, bb_tools_dir=None, hostip='169.254.0.1', port=1338, desired_capabilities={}): remote_addr = 'http://{}:{}'.format(hostip, port) filename = 'blackberry-deploy' if platform.system() == "Windows": filename += '.bat' if bb_tools_dir is not None: if os.path.isdir(bb_tools_dir): bb_deploy_location = os.path.join(bb_tools_dir, filename) if not os.path.isfile(bb_deploy_location): raise WebDriverException( 'Invalid blackberry-deploy location: {}'.format( bb_deploy_location)) else: raise WebDriverException( 'Invalid blackberry tools location, must be a directory: {}' .format(bb_tools_dir)) else: bb_deploy_location = filename """ Now launch the BlackBerry browser before allowing anything else to run. """ try: launch_args = [ bb_deploy_location, '-launchApp', str(hostip), '-package-name', 'sys.browser', '-package-id', 'gYABgJYFHAzbeFMPCCpYWBtHAm0', '-password', str(device_password) ] with open(os.devnull, 'w') as fp: p = subprocess.Popen(launch_args, stdout=fp) returncode = p.wait() if returncode == 0: # wait for the BlackBerry10 browser to load. is_running_args = [ bb_deploy_location, '-isAppRunning', str(hostip), '-package-name', 'sys.browser', '-package-id', 'gYABgJYFHAzbeFMPCCpYWBtHAm0', '-password', str(device_password) ] WebDriverWait(None, LOAD_TIMEOUT)\ .until(lambda x: subprocess.check_output(is_running_args) .find('result::true'), message='waiting for BlackBerry10 browser to load') RemoteWebDriver.__init__( self, command_executor=remote_addr, desired_capabilities=desired_capabilities) else: raise WebDriverException( 'blackberry-deploy failed to launch browser') except Exception as e: raise WebDriverException( 'Something went wrong launching blackberry-deploy', stacktrace=getattr(e, 'stacktrace', None))