def __init__(self, executable_path=None, port=0, desired_capabilities=DesiredCapabilities.SAFARI): """ Creates a new instance of the Safari driver. Starts the service and then creates new instance of Safari Driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the Environment Variable SELENIUM_SERVER_JAR - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various Safari switches). """ if executable_path is None: try: executable_path = os.environ["SELENIUM_SERVER_JAR"] except: raise Exception("No executable path given, please add one to Environment Variable \ 'SELENIUM_SERVER_JAR'") self.service = Service(executable_path, port=port) self.service.start() RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) self._is_remote = False
def __init__(self, port=None, desired_capabilities=DesiredCapabilities.PHANTOMJS): if port is None: port = 8910 class DummyService(): """Dummy service to accept the same calls as the PhantomJS webdriver.""" def __init__(self, port): self.port = port @property def service_url(self): return 'http://localhost:%d/wd/hub' % port def stop(self, *args, **kwargs): pass self.service = DummyService(port) # Start the remote web driver. try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise self._is_remote = False
def __init__(self, executable_path="chromedriver", port=0, chrome_options=None, service_args=None, desired_capabilities=None): """ Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". - chrome_options: this takes an instance of ChromeOptions """ if chrome_options is None: options = Options() else: options = chrome_options if desired_capabilities is not None: desired_capabilities.update(options.to_capabilities()) else: desired_capabilities = options.to_capabilities() self.service = Service(executable_path, port=port, service_args=service_args) self.service.start() try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise
def __init__(self, executable_path="phantomjs", port=0, desired_capabilities=DesiredCapabilities.PHANTOMJS): """ Creates a new instance of the PhantomJS / Ghostdriver. Starts the service and then creates new instance of the driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". """ self.service = Service(executable_path, port=port) self.service.start() try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise self._is_remote = False
def __init__(self, url, desired_capabilities={}): """Creates a WebDriver that controls Chrome via ChromeDriver. Args: url: The URL of a running ChromeDriver server. desired_capabilities: Requested capabilities for the new WebDriver session. """ RemoteWebDriver.__init__(self, command_executor=url, desired_capabilities=desired_capabilities) # Add custom commands. custom_commands = { WebDriver._CHROME_GET_EXTENSIONS: ('GET', '/session/$sessionId/chrome/extensions'), WebDriver._CHROME_INSTALL_EXTENSION: ('POST', '/session/$sessionId/chrome/extensions'), WebDriver._CHROME_GET_EXTENSION_INFO: ('GET', '/session/$sessionId/chrome/extension/$id'), WebDriver._CHROME_MODIFY_EXTENSION: ('POST', '/session/$sessionId/chrome/extension/$id'), WebDriver._CHROME_UNINSTALL_EXTENSION: ('DELETE', '/session/$sessionId/chrome/extension/$id'), WebDriver._CHROME_GET_VIEW_HANDLES: ('GET', '/session/$sessionId/chrome/views'), WebDriver._CHROME_DUMP_HEAP_PROFILE: ('POST', '/session/$sessionId/chrome/heapprofilerdump') } self.command_executor._commands.update(custom_commands)
def get_latest_template(browser: WebDriver, url_link): TEMPLATE_PATH = 'template' TEMPLATE_NAME = 'template.xlsx' with open('config.json') as f: config = json.load(f) browser.get(url_link) list = browser.find_element_by_id('ApplicationList') list.send_keys('Standard LDSS') core_data = browser.find_element_by_id('CoreData') core_data.click() download_btn = browser.find_element_by_css_selector('input[value = "Download"]') download_btn.click() time.sleep(10) c_dir = os.getcwd() template_path = os.path.join(c_dir, TEMPLATE_PATH) file_bef = os.listdir(template_path) if TEMPLATE_NAME in file_bef: os.remove(template_path + os.sep + TEMPLATE_NAME) time.sleep(3) for a in range(len(file_bef)): if file_bef[a] == '__init__.py': pass else: os.rename(template_path + os.sep + file_bef[a], template_path + os.sep + TEMPLATE_NAME) break
def __init__(self, executable_path="phantomjs", port=0, desired_capabilities=DesiredCapabilities.PHANTOMJS, service_args=None, service_log_path=None): """ Creates a new instance of the PhantomJS / Ghostdriver. Starts the service and then creates new instance of the driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". - service_args : A List of command line arguments to pass to PhantomJS - service_log_path: Path for phantomjs service to log to. """ warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless ' 'versions of Chrome or Firefox instead') self.service = Service( executable_path, port=port, service_args=service_args, log_path=service_log_path) self.service.start() try: RemoteWebDriver.__init__( self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except Exception: self.quit() raise self._is_remote = False
def testShouldBeGivenCapabilitiesWhenStartingASession(self): driver = WebDriver(self._launcher.GetURL(), {}) capabilities = driver.capabilities self.assertEquals("chrome", capabilities["browserName"]) self.assertTrue(capabilities["javascriptEnabled"]) # Value depends on what version the server is starting. self.assertTrue("version" in capabilities) self.assertTrue( isinstance(capabilities["version"], unicode), "Expected a %s, but was %s" % (unicode, type(capabilities["version"])), ) system = platform.system() if system == "Linux": self.assertEquals("linux", capabilities["platform"].lower()) elif system == "Windows": self.assertEquals("windows", capabilities["platform"].lower()) elif system == "Darwin": self.assertEquals("mac", capabilities["platform"].lower()) else: # No python on ChromeOS, so we won't have a platform value, but # the server will know and return the value accordingly. self.assertEquals("chromeos", capabilities["platform"].lower()) driver.quit()
def load_posts(self, *, web_driver: WebDriver = None, **params) -> List[Post]: params.setdefault('owner_id', -self.group_id) if web_driver is None: raw_posts = self.get_all_objects('wall.get', **params) else: open_url('https://vk.com', web_driver) login = web_driver.find_element_by_xpath('//*[@id="index_email"]') login.clear() login.send_keys(self.user_login) password = web_driver.find_element_by_xpath('//*[@id="index_pass"]') password.clear() password.send_keys(self.user_password) web_driver.find_element_by_xpath('//*[@id="index_login_button"]').click() url_parts = list(urlparse('https://vk.com/dev/wall.get')) count = 100 query = {'params[owner_id]': params['owner_id'], 'params[count]': count, 'params[offset]': params.get('offset', 0), 'params[filter]': params.get('filter', 'owner'), 'params[fields]': params.get('fields', ''), 'params[v]': self.api_version} url_parts[4] = urlencode(query) url = urlunparse(url_parts) response = parse_from_vk_dev(url, web_driver)['response'] total_count = response['count'] raw_posts = response['items'] while len(raw_posts) < total_count: query['params[offset]'] += count url_parts[4] = urlencode(query) url = urlunparse(url_parts) response = parse_from_vk_dev(url, web_driver)['response'] raw_posts += response['items'] return [Post.from_raw(raw_post) for raw_post in raw_posts]
def scroll_into_view(driver: WebDriver, element, offset_pixels=0): """Scrolls page to element using JS""" driver.execute_script("return arguments[0].scrollIntoView();", element) # compensate for the header driver.execute_script("window.scrollBy(0, -{});".format(offset_pixels)) return element
def __init__(self, port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT): self.port = port if self.port == 0: self.port = utils.free_port() # Create IE Driver instance of the unmanaged code try: self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"win32", "IEDriver.dll")) except WindowsError: try: self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"x64", "IEDriver.dll")) except WindowsError: raise WebDriverException("Unable to load the IEDriver.dll component") self.ptr = self.iedriver.StartServer(self.port) seconds = 0 while not utils.is_connectable(self.port): seconds += 1 if seconds > DEFAULT_TIMEOUT: raise RuntimeError("Unable to connect to IE") time.sleep(1) RemoteWebDriver.__init__( self, command_executor='http://localhost:%d' % self.port, desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
def __init__(self, executable_path="phantomjs", port=0, desired_capabilities=DesiredCapabilities.PHANTOMJS, service_args=None, service_log_path=None): """ Creates a new instance of the PhantomJS / Ghostdriver. Starts the service and then creates new instance of the driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". - service_args : A List of command line arguments to pass to PhantomJS - service_log_path: Path for phantomjs service to log to. """ self.service = Service(executable_path, port=port, service_args=service_args, log_path=service_log_path) self.service.start() command_executor = self.service.service_url try: RemoteWebDriver.__init__(self, command_executor=command_executor, desired_capabilities=desired_capabilities) except: self.quit() raise self._is_remote = False # Patch to support Native PhantomJS script self.command_executor = RemoteConnection(command_executor, keep_alive=False) Command.EXECUTE_PHANTOM_SCRIPT = "executePhantomScript" self.command_executor._commands[Command.EXECUTE_PHANTOM_SCRIPT] = ("POST", "/session/$sessionId/phantom/execute")
def __init__(self, port=0, executable_path="/usr/bin/safaridriver", reuse_service=False, desired_capabilities=DesiredCapabilities.SAFARI, quiet=False): """ Creates a new Safari driver instance and launches or finds a running safaridriver service. :Args: - port - The port on which the safaridriver service should listen for new connections. If zero, a free port will be found. - quiet - If True, the driver's stdout and stderr is suppressed. - executable_path - Path to a custom safaridriver executable to be used. If absent, /usr/bin/safaridriver is used. - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various Safari switches). - reuse_service - If True, do not spawn a safaridriver instance; instead, connect to an already-running service that was launched externally. """ self._reuse_service = reuse_service self.service = Service(executable_path, port=port, quiet=quiet) if not reuse_service: self.service.start() executor = SafariRemoteConnection(remote_server_addr=self.service.service_url) RemoteWebDriver.__init__( self, command_executor=executor, desired_capabilities=desired_capabilities) self._is_remote = False
def testShouldBeGivenCapabilitiesWhenStartingASession(self): driver = WebDriver(self._launcher.GetURL(), {}) capabilities = driver.capabilities self.assertEquals('chrome', capabilities['browserName']) self.assertTrue(capabilities['javascriptEnabled']) # Value depends on what version the server is starting. self.assertTrue('version' in capabilities) self.assertTrue( isinstance(capabilities['version'], unicode), 'Expected a %s, but was %s' % (unicode, type(capabilities['version']))) system = platform.system() if system == 'Linux': self.assertEquals('linux', capabilities['platform'].lower()) elif system == 'Windows': self.assertEquals('windows', capabilities['platform'].lower()) elif system == 'Darwin': self.assertEquals('mac', capabilities['platform'].lower()) else: # No python on ChromeOS, so we won't have a platform value, but # the server will know and return the value accordingly. self.assertEquals('chromeos', capabilities['platform'].lower()) driver.quit()
def __init__(self, executable_path="chromedriver", port=0, desired_capabilities=None, chrome_options=None): """ Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various chrome switches). This is being deprecated, please use chrome_options - chrome_options: this takes an instance of ChromeOptions """ if chrome_options is None: options = Options() else: options = chrome_options if desired_capabilities is not None: warnings.warn("Desired Capabilities has been deprecated, please user chrome_options.", DeprecationWarning) desired_capabilities.update(options.to_capabilities()) else: desired_capabilities = options.to_capabilities() self.service = Service(executable_path, port=port) self.service.start() try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise WebDriverException("The Driver was not able to start.")
def __init__(self, executable_path="WebKitWebDriver", port=0, options=None, desired_capabilities=DesiredCapabilities.WEBKITGTK, service_log_path=None, keep_alive=False): """ Creates a new instance of the WebKitGTK driver. Starts the service and then creates new instance of WebKitGTK Driver. :Args: - executable_path : path to the executable. If the default is used it assumes the executable is in the $PATH. - port : port you would like the service to run, if left as 0, a free port will be found. - options : an instance of WebKitGTKOptions - desired_capabilities : Dictionary object with desired capabilities - service_log_path : Path to write service stdout and stderr output. - keep_alive : Whether to configure RemoteConnection to use HTTP keep-alive. """ if options is not None: capabilities = options.to_capabilities() capabilities.update(desired_capabilities) desired_capabilities = capabilities self.service = Service(executable_path, port=port, log_path=service_log_path) self.service.start() RemoteWebDriver.__init__( self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities, keep_alive=keep_alive) self._is_remote = False
def __init__(self, executable_path=os.environ['OPENSHIFT_REPO_DIR']+"PhantomJSpatched/phantomjs", ip='127.0.0.1', port=0, desired_capabilities=DesiredCapabilities.PHANTOMJS, service_args=None, service_log_path=None): """ Creates a new instance of the PhantomJS / Ghostdriver. Starts the service and then creates new instance of the driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". - service_args : A List of command line arguments to pass to PhantomJS - service_log_path: Path for phantomjs service to log to. """ self.service = Service(executable_path,ip=ip, port=port, service_args=service_args, log_path=service_log_path) self.service.start() try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise self._is_remote = False
def __init__(self, device_password, bb_tools_dir=None, hostip='169.254.0.1', port=1338, desired_capabilities={}): import warnings warnings.warn('BlackBerry Driver is no longer supported and will be ' 'removed in future versions', DeprecationWarning, stacklevel=2) 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))
def __init__(self, executable_path='IEDriverServer.exe', port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT): self.port = port if self.port == 0: self.port = utils.free_port() try: self.iedriver = Service(executable_path, port=self.port) self.iedriver.start() except: # Create IE Driver instance of the unmanaged code try: warnings.warn("You need to download the IEDriverServer. \ Using the deprecated approach", DeprecationWarning) self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"win32", "IEDriver.dll")) except WindowsError: try: self.iedriver = CDLL(os.path.join(os.path.dirname(__file__),"x64", "IEDriver.dll")) except WindowsError: raise WebDriverException("Unable to load the IEDriver.dll component") self.ptr = self.iedriver.StartServer(self.port) seconds = 0 while not utils.is_url_connectable(self.port): seconds += 1 if seconds > DEFAULT_TIMEOUT: # Clean up after ourselves self.quit() raise RuntimeError("Unable to connect to IE") time.sleep(1) RemoteWebDriver.__init__( self, command_executor='http://localhost:%d' % self.port, desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
def __init__(self, firefox_profile=None, firefox_binary=None, timeout=30, capabilities=None, proxy=None): self.binary = firefox_binary self.profile = firefox_profile if self.profile is None: self.profile = FirefoxProfile() self.profile.native_events_enabled = ( self.NATIVE_EVENTS_ALLOWED and self.profile.native_events_enabled) if self.binary is None: self.binary = FirefoxBinary() if capabilities is None: capabilities = DesiredCapabilities.FIREFOX if proxy is not None: proxy.add_to_capabilities(capabilities) RemoteWebDriver.__init__(self, command_executor=ExtensionConnection("127.0.0.1", self.profile, self.binary, timeout), desired_capabilities=capabilities, keep_alive=True) self._is_remote = False
def __init__(self, params=None, firefox_profile=None, firefox_binary=None, timeout=30): self.binary = firefox_binary self.profile = firefox_profile if self.profile is None: self.profile = FirefoxProfile() if self.binary is None: self.binary = FirefoxBinary() COMMAND_EXECUTOR = ExtensionConnection if type(COMMAND_EXECUTOR) == str: cmd_executor = COMMAND_EXECUTOR else: cmd_executor = COMMAND_EXECUTOR( "127.0.0.1", self.profile, self.binary, timeout ) RemoteWebDriver.__init__(self, command_executor=cmd_executor, desired_capabilities=DesiredCapabilities.FIREFOX)
def __init__(self, executable_path='IEDriverServer.exe', capabilities=None, port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT, host=DEFAULT_HOST, log_level=DEFAULT_LOG_LEVEL, log_file=DEFAULT_LOG_FILE): self.port = port if self.port == 0: self.port = utils.free_port() self.host = host self.log_level = log_level self.log_file = log_file self.iedriver = Service( executable_path, port=self.port, host=self.host, log_level=self.log_level, log_file=self.log_file) self.iedriver.start() if capabilities is None: capabilities = DesiredCapabilities.INTERNETEXPLORER RemoteWebDriver.__init__( self, command_executor='http://localhost:%d' % self.port, desired_capabilities=capabilities) self._is_remote = False
def __init__(self, executable_path="phantomjs", port=0, desired_capabilities=DesiredCapabilities.PHANTOMJS, pre_command=None, service_args=None, service_log_path=None): """ Creates a new instance of the PhantomJS / Ghostdriver. Starts the service and then creates new instance of the driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". - pre_command : Is in case the 'executable_path' has to bee called in another command. e.g.: if network namespaces are used, we need to execute phantom after 'ip netns exec <namespace_name>' - service_args : A List of command line arguments to pass to PhantomJS - service_log_path: Path for phantomjs service to log to. """ self.service = ServicePhantomjsExtended(executable_path, port=port, pre_command=pre_command, service_args=service_args, log_path=service_log_path) self.service.start() try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise self._is_remote = False
def quit(self): RemoteWebDriver.quit(self) try: self.iedriver.stop() except: self.iedriver.StopServer(self.ptr) del self.iedriver del self.ptr
def quit(self): """ Closes the browser and shuts down the """ try: RemoteWebDriver.quit(self) except http_client.BadStatusLine: pass
def quit(self): """ Close AndroidDriver application on device""" try: RemoteWebDriver.quit(self) except httplib.BadStatusLine: pass finally: self.service.stop()
def close_tab(window_name: str, web_driver: WebDriver): while True: try: web_driver.close() web_driver.switch_to.window(window_name) return except TimeoutException: continue
def test_get_url(): sleep(10) TEST_URL = "http://httpbin/html" driver = WebDriver("http://%s:%s/wd/hub" % (SELENIUM_HOST, SELENIUM_PORT), desired_capabilities={"browserName": "phantomjs"}) driver.get(TEST_URL) elem = driver.find_element_by_tag_name("h1") assert "Moby-Dick" in elem.text
def testSendKeysNative(self): driver = WebDriver(self._launcher.GetURL(), self._capabilities) driver.get(self._launcher.GetURL() + '/test_page.html') # Find the text input. q = driver.find_element_by_name("key_input_test") # Send some keys. q.send_keys("tokyo") #TODO(timothe): change to .text when beta 4 wrappers are out. self.assertEqual(q.value, "tokyo")
def quit(self): """Quits the driver and close every associated window.""" try: RemoteWebDriver.quit(self) except httplib.BadStatusLine: # Happens if Firefox shutsdown before we've read the response from # the socket. pass self.browser.kill()
def verificar_display_flex_modal_mensaje_de_exito(web_driver: WebDriver): try: while True: lista_div_containers = web_driver.find_elements_by_class_name( 'NotificationContainer') if len(lista_div_containers) > 0: pass elif len(lista_div_containers) == 0: break except NoSuchElementException: pass
def capture_viewport(cls, name: str, driver: WebDriver, scale: float = 1.0) -> Screenshot: """ Creates a screenshot of the current viewport of a given webdriver. Scales the image by some pixel ratio, if given. Uses PIL as a backend. """ page_screenshot_png_bytes = driver.get_screenshot_as_png() image = Image.open(io.BytesIO(page_screenshot_png_bytes)).convert("RGB") if scale != 1.0: new_size = [int(x * scale) for x in image.size] image = image.resize(new_size) return Screenshot(name, image)
def run(self, driver: WebDriver): for step in self.steps: element = None print(step) if isinstance(step, dict): if "id" in step.keys(): element = driver.find_element_by_id(step["id"]) elif "xpath" in step.keys(): element = driver.find_element_by_xpath(step["xpath"]) else: print(step.keys()) if "input" in step.keys(): element.send_keys(step["input"]) else: element.click() if "get" in step.keys(): text = element.get_attribute(step["get"]) print(text)
def dump_heap_profile(self, reason): """Dumps a heap profile. It works only on Linux and ChromeOS. We need an environment variable "HEAPPROFILE" set to a directory and a filename prefix, for example, "/tmp/prof". In a case of this example, heap profiles will be dumped into "/tmp/prof.(pid).0002.heap", "/tmp/prof.(pid).0003.heap", and so on. Nothing happens when this function is called without the env. Args: reason: A string which describes the reason for dumping a heap profile. The reason will be included in the logged message. Examples: 'To check memory leaking' 'For WebDriver tests' """ if self.IsLinux(): # IsLinux() also implies IsChromeOS(). params = {'reason': reason} RemoteWebDriver.execute(self, WebDriver._CHROME_DUMP_HEAP_PROFILE, params) else: raise WebDriverException('Heap-profiling is not supported in this OS.')
def mode_remote(self, browser_name='chrome'): """Open new brower on remote mode Raises: CoreException -- browser name is not in valid values list """ url_hub = self.settings.get('url_hub') self.log.debug('Starting browser with mode : REMOTE ...') self.curr_driver = RemoteWebDriver(command_executor=url_hub, desired_capabilities=self.curr_caps, options=self.curr_options) self.log.info('Started browser with mode : REMOTE OK')
def __init__(self, port=0, desired_capabilities=DesiredCapabilities.SAFARI, quiet=False): """ Creates a new instance of the Safari driver. Starts the service and then creates new instance of Safari Driver. :Args: - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various Safari switches). - quiet - set to True to suppress stdout and stderr of the driver """ self.service = Service(port=port, quiet=quiet) self.service.start() RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) self._is_remote = False
def scroll_to(driver: WebDriver, element: WebElement): if "firefox" in driver.capabilities["browserName"].lower(): view_port_height = int( driver.execute_script("return window.innerHeight;")) vertical_position = int(element.location["y"]) if vertical_position > view_port_height: logging.debug(f"Scrolling to y={vertical_position}") driver.execute_script(f"window.scrollTo(0, {vertical_position});") else: logging.debug( f"Element is already positioned ({vertical_position}) within view_port " f"({view_port_height})") if not element.is_displayed(): logging.debug( f"Scrolling to element using scrollIntoView: {element}") driver.execute_script(f"arguments[0].scrollIntoView(true);", element) else: action_chains = ActionChains(driver) action_chains.move_to_element(element) action_chains.perform()
def check_message(browser: WebDriver) -> list: ret_m = [] skip_texts = ['', 'Sent from Mobile', 'Sent from Messenger', 'Sent from Web'] messages = browser.find_elements_by_css_selector('#messageGroup > div:nth-child(2) span') for message in messages: text = message.text if text in skip_texts: continue if regex.match(text): ret_m = [] ret_m.append(text) return ret_m
def test_js_dev_cdn(self, version: str, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: Tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "1.4.0rc1") monkeypatch.setattr(resources, "__version__", "1.4.0rc1") js, tag = bes.autoload_static(test_plot, CDN, "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(By.CSS_SELECTOR, 'head script') assert len(scripts) == 5 for script in scripts: assert script.get_attribute("crossorigin") is None assert script.get_attribute("integrity") == ""
def is_element_present(driver: WebDriver, selector: Selector) -> bool: """Check if sought element is present""" try: elements = driver.find_elements(by=selector.by, value=selector.value) if elements: logging.debug(f"Found following elements: {elements}") found = True else: found = False except NoSuchElementException: found = False return found
def __init__(self, profile=None, timeout=30): """Creates a webdriver instance. Args: profile: a FirefoxProfile object (it can also be a profile name, but the support for that may be removed in future, it is recommended to pass in a FirefoxProfile object) timeout: the amount of time to wait for extension socket """ port = self._free_port() self.browser = FirefoxLauncher() if type(profile) == str: # This is to be Backward compatible because we used to take a # profile name profile = FirefoxProfile(name=profile, port=port) if not profile: profile = FirefoxProfile(port=port) self.browser.launch_browser(profile) RemoteWebDriver.__init__(self, command_executor=ExtensionConnection(timeout), desired_capabilities=DesiredCapabilities.FIREFOX)
def __init__(self, port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT): self.port = port if self.port == 0: self.port = utils.free_port() # Create IE Driver instance of the unmanaged code self.iedriver = CDLL( os.path.join(os.path.dirname(__file__), "IEDriver.dll")) self.ptr = self.iedriver.StartServer(self.port) seconds = 0 while not utils.is_connectable(self.port): seconds += 1 if seconds > DEFAULT_TIMEOUT: raise RuntimeError("Unable to connect to IE") time.sleep(1) RemoteWebDriver.__init__( self, command_executor='http://localhost:%d' % self.port, desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
def establecer_vista_de_archivos_como_lista(webdriver: WebDriver): boton_vista = webdriver.find_element_by_xpath( '//div[@class="icon view-toggle"]') tool_tip = boton_vista.find_element_by_class_name('amx-tooltip') tool_tip = tool_tip.get_attribute('innerHTML') tool_tip = tool_tip.strip() if tool_tip == 'Vista lista': HtmlActions.webdriver_wait_until_not_presence_of_element_located( webdriver, 15, xpath='//div[@class="row type-success"]') boton_vista.click()
def user_profile_is_loaded(driver: WebDriver) -> bool: if driver.current_url != "https://24.play.pl/Play24/Welcome": return False if not find_balance_button(driver): return False for loader in driver.find_elements_by_css_selector(".loader-content"): try: if loader.is_displayed(): return False except StaleElementReferenceException: return False return True
def _maximize_viewport(web_driver: WebDriver) -> Tuple[int, int, int]: calculate_viewport_size = """\ const root = document.getElementsByClassName("bk-root")[0] const {width, height} = root.children[0].getBoundingClientRect() return [width, height, window.devicePixelRatio] """ viewport_size: Tuple[int, int, int] = web_driver.execute_script( calculate_viewport_size) calculate_window_size = """\ const [width, height, dpr] = arguments return [ // XXX: outer{Width,Height} can be 0 in headless mode under certain window managers Math.max(0, window.outerWidth - window.innerWidth) + width*dpr, Math.max(0, window.outerHeight - window.innerHeight) + height*dpr, ] """ [width, height] = web_driver.execute_script(calculate_window_size, *viewport_size) eps = 100 # XXX: can't set window size exactly in certain window managers, crop it to size later web_driver.set_window_size(width + eps, height + eps) return viewport_size
def read_services(driver: WebDriver, timeout: int) -> str: services_url = "https://24.play.pl/Play24/Services" def services_page_is_loaded(driver: WebDriver) -> bool: if driver.current_url != services_url: return False for loader in driver.find_elements_by_css_selector(".loader-content"): try: if loader.is_displayed(): return False except StaleElementReferenceException: return False return True wait = WebDriverWait(driver, timeout) driver.get(services_url) wait.until(services_page_is_loaded) services_element = driver.find_element_by_css_selector( ".container.services") services_html: str = services_element.get_property("innerHTML") return services_html
def quit(self): """Quits the driver and close every associated window.""" try: RemoteWebDriver.quit(self) except (http_client.BadStatusLine, socket.error): # Happens if Firefox shutsdown before we've read the response from # the socket. pass if self.w3c: self.service.stop() else: self.binary.kill() if self.profile is not None: try: shutil.rmtree(self.profile.path) if self.profile.tempfolder is not None: shutil.rmtree(self.profile.tempfolder) except Exception as e: print(str(e))
def test_can_access_password_reset_page(selenium: WebDriver): selenium.get(base_url) selenium.find_element_by_id("SignInButton").click() selenium.find_element_by_id("ForgotPasswordLink").click() assert selenium.current_url == base_url + "accounts/password_reset/"
def test_cant_registrate_with_empty_fields(selenium: WebDriver): selenium.get(base_url) selenium.find_element_by_id("SignUpButton").click() selenium.find_element_by_id("SubmitSignUpButton").click() assert selenium.current_url == base_url + "accounts/sign_up/"
def recognize_captcha(driver: WebDriver, devicePixelRatio, imgFilePath, is_tensorflow_recognise_captcha, tujian_username=None, tujian_pwd=None): verifyCodeImgElement = WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.ID, "captcha"))) # 获取验证码位置信息 verifyCodeImgLocation = verifyCodeImgElement.location verifyCodeImgSize = verifyCodeImgElement.size verifyCodeImgLeft = verifyCodeImgLocation['x'] verifyCodeImgTop = verifyCodeImgLocation['y'] verifyCodeImgRight = verifyCodeImgLeft + verifyCodeImgSize['width'] verifyCodeImgBottom = verifyCodeImgTop + verifyCodeImgSize['height'] # 登录页面全屏截图 driver.get_screenshot_as_file(imgFilePath) # 从全屏截图 截取验证码区域 verifyCodeImg = Image.open(imgFilePath).crop( (verifyCodeImgLeft * devicePixelRatio, verifyCodeImgTop * devicePixelRatio, verifyCodeImgRight * devicePixelRatio, verifyCodeImgBottom * devicePixelRatio)) w, h = verifyCodeImg.size verifyCodeImg.thumbnail((w / devicePixelRatio, h / devicePixelRatio)) verifyCodeImg = verifyCodeImg.convert('L') # 转换模式 L|RGB verifyCodeImg = ImageEnhance.Contrast(verifyCodeImg) # 增强对比度 verifyCodeImg = verifyCodeImg.enhance(2.0) # 增加饱和度 verifyCodeImg.save(imgFilePath) if is_tensorflow_recognise_captcha: verifyCode = tensorflow_recognize(imgFilePath) else: verifyCode = tujian_api_helper.img_recognise(tujian_username, tujian_pwd, imgFilePath) new_image_path = veryeast_config.SCREEN_IMG_DIR + "/" + verifyCode.upper( ) + "_" + TimeUtils.microsecondStr() + ".png" if verifyCode: os.rename(imgFilePath, new_image_path) return [verifyCode, new_image_path]
def test_settings_update_tags(selenium: WebDriver) -> None: register_valid_user(selenium) selenium.get(f'{URL}settings/tags') add_button = selenium.find_elements_by_tag_name('button')[1] add_button.click() # add a tag fill_form(selenium, {'name': 'python'}, is_category=False) tbody_td = selenium.find_element_by_tag_name( 'tbody').find_elements_by_tag_name('td') assert 'python' in tbody_td[1].text assert '0' in tbody_td[2].text edit_icon = tbody_td[3].find_element_by_class_name('fa-pencil') assert len(tbody_td[3].find_elements_by_class_name('fa-trash')) == 1 # edit the tag edit_icon.click() fill_form(selenium, {'name': 'tests'}, is_category=False) tbody_td = selenium.find_element_by_tag_name( 'tbody').find_elements_by_tag_name('td') assert 'tests' in tbody_td[1].text # delete the tag tbody_td[3].find_element_by_class_name('fa-trash').click() tbody_td = selenium.find_element_by_tag_name( 'tbody').find_elements_by_tag_name('td') assert tbody_td == []
def find_and_select_random_funding_options(driver: WebDriver, position: str, amount: str): # every call of this function, click on Add Goal find_and_click(driver, element_selector_name="Add a funding option") driver.implicitly_wait(5) actual_positon = 1 if int(position) != 1: actual_positon = int(position) + (int(position) - 1) # funding_option_element_xpath = "//body/main/div[2]/div/div/div[2]/div/div[3]/div[1]/table/tbody/tr" + "[" + str(actual_positon) + "]" # funding_option_1_element = funding_option_element_xpath + "/td[1]/div/div/div[2]/button" # driver.find_element_by_xpath(funding_option_1_element).click() # driver.implicitly_wait(5) # # #driver.implicitly_wait(5) # #/html/body/main/div[2]/div/div/div[2]/div/div[3]/div[1]/table/tbody/tr[1]/td[1]/div/div/ul/li[3] # ulist_funding_options_xpath = "//body/main/div[2]/div/div/div[2]/div/div[3]/div[1]/table/tbody/tr[1]/td[1]/div/div/ul" # ulist_funding_options_element = driver.find_element_by_xpath(ulist_funding_options_xpath) # funding_options_elements = ulist_funding_options_element.find_elements_by_tag_name("li") # # random_number = 0 # if len(funding_options_elements) > 2: # random_number = random.randint(1, len(funding_options_elements) - 1) # #random_li_element = funding_options_elements[random_number] # #random_li_element.click() # random_li_element = driver.find_element_by_xpath(ulist_funding_options_xpath + "/li[" + str(random_number) + "]") # random_li_element.click() # time.sleep(2) gbp_elem_xpath = "//body/main/div[2]/div/div/div[2]/div/div[3]/div[1]/table/tbody/tr" + "[" + str( actual_positon) + "]" gbp_text_elem_xpath = gbp_elem_xpath + "/td[2]/div/div[2]/input" driver.find_element_by_xpath(gbp_text_elem_xpath).clear() driver.find_element_by_xpath(gbp_text_elem_xpath).send_keys(amount) time.sleep(2)
def ff_driver(request): timeout = 10000 capabilities = webdriver.DesiredCapabilities.FIREFOX.copy() capabilities['timeouts'] = { 'implicit': timeout, 'pageLoad': timeout, 'script': timeout } capabilities['loggingPrefs'] = { 'browser': 'ALL', 'client': 'ALL', 'driver': 'ALL', 'performance': 'ALL', 'server': 'ALL' } profile = webdriver.FirefoxProfile() profile.set_preference('app.update.auto', False) profile.set_preference('app.update.enabled', False) profile.accept_untrusted_certs = True wd = WebDriver(browser_profile=profile, desired_capabilities=capabilities) wd.maximize_window() yield wd wd.quit()
def delete_all_trip_details(driver: WebDriver, del_button_position: str): # 1,3,5,7,...... trip_text_area_element_index = int(del_button_position) - 1 trip_text_area_element_x_path = "/html/body/main/div[2]/section[6]/div/div[2]/div/div[2]/table/tbody/tr" \ + "[" + str(trip_text_area_element_index) + "]" + "/td/div/textarea" trip_text_area_text_exists = True try: trip_text_area_text = driver.find_element_by_xpath(trip_text_area_element_x_path).text if trip_text_area_text == None or len(trip_text_area_text) <= 0: trip_text_area_text_exists = False except: trip_text_area_text_exists = False # del_button_position: 2,4,6,8,10,..... document_div_element_xpath = "/html/body/main/div[2]/section[6]/div/div[2]/div/div[2]/table/tbody/tr" + "[" + del_button_position + "]" del_btn_ele_xpath = document_div_element_xpath + "/td/button/i" driver.find_element_by_xpath(del_btn_ele_xpath).click() if trip_text_area_text_exists == True: driver.implicitly_wait(1) # 12,13,14,15....... # 12 + (2/2 - 1), 12 + (4/2 - 1), 12 + (6/2 - 1), 12 + (8/2 - 1),......... delete_msg_yes_index = int(12 + (int((int(del_button_position) / 2)) - 1)) delete_message_yes_element_xpath = "//body/div" + "[" + str( delete_msg_yes_index) + "]" + "/div/div/div/div[2]/div[2]/button[1]" delete_message_yes_element = driver.find_element_by_xpath(delete_message_yes_element_xpath) delete_message_yes_element.click() time.sleep(1)
def wait_until_render_complete(driver: WebDriver, timeout: int) -> None: ''' ''' from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.wait import WebDriverWait def is_bokeh_loaded(driver: WebDriver) -> bool: return cast( bool, driver.execute_script(''' return typeof Bokeh !== "undefined" && Bokeh.documents != null && Bokeh.documents.length != 0 ''')) try: WebDriverWait(driver, timeout, poll_frequency=0.1).until(is_bokeh_loaded) except TimeoutException as e: _log_console(driver) raise RuntimeError( 'Bokeh was not loaded in time. Something may have gone wrong.' ) from e driver.execute_script(_WAIT_SCRIPT) def is_bokeh_render_complete(driver: WebDriver) -> bool: return cast( bool, driver.execute_script('return window._bokeh_render_complete;')) try: WebDriverWait(driver, timeout, poll_frequency=0.1).until(is_bokeh_render_complete) except TimeoutException: log.warning( "The webdriver raised a TimeoutException while waiting for " "a 'bokeh:idle' event to signify that the layout has rendered. " "Something may have gone wrong.") finally: _log_console(driver)
def find_and_click_on_page_element(driver: WebDriver, sections: dict, element_name: str, *, wait_for_it: bool = True): """Find page element in any page section selectors and click on it.""" found_selector = False logging.debug(sections) for section_name, selectors in sections.items(): if element_name.lower() in selectors: found_selector = True selector = selectors[element_name.lower()] logging.debug( f"Found selector for '{element_name}' in '{section_name}' section: " f"'{selector}'") web_element = find_element(driver, selector, element_name=element_name, wait_for_it=wait_for_it) check_if_element_is_visible(web_element, element_name) if web_element.get_attribute("target") == "_blank": logging.debug( f"'{web_element.text}' opens in new tab, but will " f"forcefully open it in the same one") with wait_for_page_load_after_action(driver): href = web_element.get_attribute("href") driver.get(href) else: scroll_to(driver, web_element) if selector.wait_after_click: with wait_for_page_load_after_action(driver, timeout=10): with try_alternative_click_on_exception( driver, web_element): web_element.click() else: with try_alternative_click_on_exception( driver, web_element): web_element.click() with assertion_msg(f"Could not find '{element_name}' in any section"): assert found_selector
def _set_time(driver: WebDriver, upload_time: datetime): # Start time scheduling WebDriverWait(driver, 20).until(EC.element_to_be_clickable( (By.NAME, "SCHEDULE"))).click() # Open date_picker driver.find_element_by_css_selector( "#datepicker-trigger > ytcp-dropdown-trigger:nth-child(1)").click() date_input: WebElement = driver.find_element_by_css_selector( "input.tp-yt-paper-input") date_input.clear() # Transform date into required format: Mar 19, 2021 date_input.send_keys(upload_time.strftime("%b %d, %Y")) date_input.send_keys(Keys.RETURN) # Open time_picker driver.find_element_by_css_selector( "#time-of-day-trigger > ytcp-dropdown-trigger:nth-child(1) > div:nth-child(2)" ).click() time_list = driver.find_elements_by_css_selector( "tp-yt-paper-item.tp-yt-paper-item") # Transform time into required format: 8:15 PM time_str = upload_time.strftime("%I:%M %p").strip("0") time = [time for time in time_list[2:] if time.text == time_str][0] time.click()
def upload_file( driver: WebDriver, video_path: str, title: str, description: str, game: str, kids: bool, upload_time: datetime, thumbnail_path: str = None, ): WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ytcp-button#create-icon"))).click() WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.XPATH, '//tp-yt-paper-item[@test-id="upload-beta"]')) ).click() video_input = driver.find_element_by_xpath('//input[@type="file"]') video_input.send_keys(video_path) _set_basic_settings(driver, title, description, thumbnail_path) _set_advanced_settings(driver, game, kids) # Go to visibility settings for i in range(3): WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "next-button"))).click() _set_time(driver, upload_time) _wait_for_processing(driver) # Go back to endcard settings driver.find_element_by_css_selector("#step-badge-1").click() _set_endcard(driver) for _ in range(2): # Sometimes, the button is clickable but clicking it raises an error, so we add a "safety-sleep" here sleep(5) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "next-button"))).click() sleep(5) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "done-button"))).click() # Wait for the dialog to disappear sleep(5) logging.info("Upload is complete")
def test_accepts_firefox_options_to_remote_driver(mocker, browser_name): options = import_module(f'selenium.webdriver.{browser_name}.options') caps_name = browser_name.upper() if browser_name != 'ie' else 'INTERNETEXPLORER' mock = mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.start_session') opts = options.Options() opts.add_argument('foo') expected_caps = getattr(DesiredCapabilities, caps_name) caps = expected_caps.copy() expected_caps.update(opts.to_capabilities()) WebDriver(desired_capabilities=caps, options=opts) mock.assert_called_with(expected_caps, None)