def _wait_until_connectable(self): """Blocks until the extension is connectable in the firefox. The base class implements this by checking utils.is_connectable() every second (sleep_for == 1) and failing after 30 attempts (max_tries == 30). Expriments showed that once a firefox can't be connected to, it's better to start a new one instead so we don't wait 30 seconds to fail in the end (the caller should catch WebDriverException and starts a new firefox). """ connectable = False max_tries = 6 sleep_for = 1 for count in range(1, max_tries): connectable = utils.is_connectable(self.profile.port) if connectable: break logger.debug( 'Cannot connect to process %d with port: %d, count %d' % (self.process.pid, self.profile.port, count)) if self.process.poll() is not None: # Browser has exited raise selenium_exceptions.WebDriverException( "The browser appears to have exited " "before we could connect. The output was: %s" % self._get_firefox_output()) time.sleep(sleep_for) if not connectable: self.kill() raise selenium_exceptions.WebDriverException( 'Cannot connect to the selenium extension, Firefox output: %s' % (self._get_firefox_output(), )) return connectable
def get_browser(ff_log_file, proxy_port=None, flash_support=cm.FLASH_ENABLE, cookie_support=cm.COOKIE_ALLOW_ALL): ff_log_file_handle = open(ff_log_file, "a+") ff_bin = FirefoxBinary(firefox_path=cm.FF_MOD_BIN, log_file=ff_log_file_handle) ffp = webdriver.FirefoxProfile(None) set_ff_prefs(ffp, proxy_port, flash_support, cookie_support) tries = 0 for tries in xrange(MAX_GET_DRIVER_TRIES): try: driver = webdriver.Firefox(firefox_profile=ffp, firefox_binary=ff_bin) except sel_exceptions.WebDriverException as wdexc: print "Error creating webdriver, will sleep (tried %s times) %s" %\ (tries, wdexc) sleep(1) # each call to webdriver constructor already takes 30 s else: if tries: print "Created the webdriver after sleeping %s sec" % (tries) break tries += 1 else: raise sel_exceptions.WebDriverException("Cannot initialize webdriver") driver.set_page_load_timeout(cm.HARD_TIME_OUT - 5) driver.implicitly_wait(10) return driver, ffp.profile_dir, ff_bin.process
def clear(self, selector): """Clear text out of input identified by CSS selector""" try: self.get_visible_element(selector).clear() except (exceptions.InvalidElementStateException, exceptions.WebDriverException): raise exceptions.WebDriverException( 'You cannot clear that element')
def test_invalid_URL_throws_error(self): self.mock_driver.get.side_effect = ( exceptions.WebDriverException('Failed to load test UI.')) result = html5_driver.NdtHtml5SeleniumDriver(browser='firefox', url='invalid_url', timeout=1).perform_test() self.assertErrorMessagesEqual(['Failed to load test UI.'], result.errors)
def test_load_url_adds_error_when_loading_url_fails(self): mock_driver = mock.Mock(spec=browser_client_common.webdriver.Firefox) mock_driver.get.side_effect = exceptions.WebDriverException( 'dummy exception') errors = [] self.assertFalse(browser_client_common.load_url( mock_driver, 'http://fake.url/foo', errors)) self.assertErrorMessagesEqual( ['Failed to load URL: http://fake.url/foo'], errors)
def Type(self, target, text, end_with_enter=False): element = self.WaitUntil(self.GetVisibleElement, target) element.clear() element.send_keys(text) if end_with_enter: element.send_keys(keys.Keys.ENTER) # We experienced that Selenium sometimes swallows the last character of the # text sent. Raising an exception here will just retry in that case. if not end_with_enter: if text != self.GetValue(target): raise exceptions.WebDriverException("Send_keys did not work correctly.")
def test_invalid_URL_throws_error(self): self.mock_browser.get.side_effect = exceptions.WebDriverException( u'Failed to load test UI.') test_results = html5_driver.NdtHtml5SeleniumDriver( browser='firefox', url='invalid_url', timeout=1).perform_test() # We have one error self.assertEqual(len(test_results.errors), 1) # And that error is about test UI loading failure self.assertEqual(test_results.errors[0].message, 'Failed to load test UI.')
def wrapper(*args, **kwargs): t = timeout print "DEBUG : Running %s on webElement : %s,%s " % (function, args, kwargs) while t != 0: try: return function(*args, **kwargs) except exceptions.WebDriverException: print "Cannot Locate Element. Retrying in %s sec(s)" % timeDelta time.sleep(timeDelta) t -= 1 raise exceptions.WebDriverException( "Element not found Exiting! Element : %s " % args[1].getSelector())
def getPath(): os.chdir(os.path.dirname(os.path.abspath(__file__))) if os.path.exists('chromedriver.exe') == False: raise exceptions.WebDriverException('driver not in directory')
def try_to_do(vic_step, func, print_=True): err = None _success = False _full_msg = '' msg = '超时' msg_format = '经过{:.1f}秒 - {}' pause_time = 0 element, el_msg, err_msg, _elapsed_time, _pause_time = get_element( vic_step, print_=print_, necessary=False) pause_time += _pause_time if element: vic_step.dr.implicitly_wait(0) timeout = vic_step.timeout - _elapsed_time if vic_step.timeout - _elapsed_time > 1 else 1 highlight_for_a_moment( vic_step.dr, [element], 'outline: 2px dotted yellow; border: 1px solid yellow;') last_print_time = start_time = time.time() while (time.time() - start_time - pause_time) <= timeout and not vic_step.force_stop: err = None try: msg = func(element=element, el_msg=el_msg) _success = True except exceptions.ElementNotVisibleException as e: err = e msg = '无法操作元素{},因为不可见'.format(el_msg) except exceptions.InvalidElementStateException as e: err = e msg = '无法操作元素{},因为无法交互,例如元素被设置为disabled'.format(el_msg) except exceptions.WebDriverException as e: _err_msg = 'element is not attached to the page document' if isinstance(e, exceptions.StaleElementReferenceException ) or _err_msg in e.msg: raise # 如果是元素过期,直接抛出异常让step处理 else: err = e msg = '无法操作元素{},因为{}'.format(el_msg, getattr(e, 'msg', str(e))) # _err_msg = 'element is not attached to the page document' # if isinstance(e, exceptions.StaleElementReferenceException) or _err_msg in e.msg: # msg = '无法操作元素{},可能是由于页面异步刷新导致,将尝试重新获取元素'.format(el_msg) # _timeout = timeout - (time.time() - start_time - pause_time) # element, el_msg, err_msg, _elapsed_time, _pause_time = get_element( # vic_step, timeout=_timeout, print_=print_, necessary=False) # pause_time += _pause_time # else: # err = e # msg = '无法操作元素{},因为{}'.format(el_msg, getattr(e, 'msg', str(e))) if time.time() - last_print_time >= 1: pause_time += vic_step.pause_() elapsed_time = time.time( ) - start_time - pause_time + _elapsed_time _full_msg = msg_format.format(elapsed_time, msg) if print_: vic_step.logger.info('【{}】\t{}'.format( vic_step.execute_str, _full_msg)) last_print_time = time.time() if _success: break vic_step.dr.implicitly_wait(vic_step.timeout) else: err = exceptions.NoSuchElementException(err_msg) msg = err_msg start_time = time.time() elapsed_time = time.time() - start_time - pause_time + _elapsed_time full_msg = msg_format.format(elapsed_time, msg) if print_ and full_msg != _full_msg: vic_step.logger.info('【{}】\t{}'.format(vic_step.execute_str, full_msg)) if _success: run_result = ['p', full_msg] else: if err: err.msg = full_msg raise err else: raise exceptions.WebDriverException(full_msg) return run_result, element, elapsed_time, pause_time
proxy_type = input('Default Proxy Type [socks/https]: ') with open(proxy, 'r') as file: proxy = file.readlines() if proxy_type == 'socks': socks_version = int(input('Socks Version [4/5]: ')) with open(combo, 'r') as file: for line in file: try: username, password = line.strip().split(':') while True: driver = get_driver( *get_proxy(proxy, proxy_type, socks_version)) try: res = login(driver, username, password) if res == 'proxy_error': raise serror.WebDriverException( "proxyConnectFailure") elif res == 'login_error': print(f'Login Error {username}:{password}') break elif res == 'login_success': print( f'Successfully Login at {username}:{password}') good_log(combo, username, password) break else: break except serror.WebDriverException as err: if 'proxyConnectFailure' in err.msg: if driver.profile.default_preferences.get( 'network.proxy.socks'): p = driver.profile.default_preferences.get