How to use wait_for_presence method in pom

Best Python code snippet using pom_python

tradingview_controller.py

Source:tradingview_controller.py Github

copy

Full Screen

...20 wait.until(lambda driver: driver.execute_script('return jQuery.active') == 0)21 wait.until(lambda driver: driver.execute_script('return document.readyState') == 'complete')22 except Exception as e:23 pass24def wait_for_presence(driver, by, element):25 wait_for_ajax(driver)26 WebDriverWait(driver, 10).until(EC.presence_of_element_located((by, element)))27def wait_for_text_presence(driver, by, element, text):28 wait_for_ajax(driver)29 WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((by, element), text))30def element_exists(driver, by, element):31 return len(driver.find_elements(by, element)) > 032def driver_has_quit(driver):33 try:34 driver.title35 return False36 except Exception as e:37 return True38def log_in():39 email = os.getenv('TRADINGVIEW_EMAIL')40 password = os.getenv('TRADINGVIEW_PASSWORD')41 driver = get_selenium_driver_instance()42 driver.get('https://www.tradingview.com/')43 wait_for_presence(driver, By.CSS_SELECTOR, '[class*="tv-header__link--signin"]')44 driver.find_element_by_css_selector('[class*="tv-header__link--signin"]').click()45 wait_for_presence(driver, By.CSS_SELECTOR, '[class*="js-show-email"]')46 driver.find_element_by_css_selector('[class*="js-show-email"]').click()47 wait_for_presence(driver, By.CSS_SELECTOR, '[class="tv-button__loader"]')48 driver.find_element_by_name('username').send_keys(email)49 driver.find_element_by_name('password').send_keys(password)50 driver.find_element_by_css_selector('[class="tv-button__loader"]').click()51 time.sleep(1)52 if element_exists(driver, By.CSS_SELECTOR, '[title="recaptcha challenge"]'):53 # for recaptchav3, grecaptcha.execute(window.RECAPTCHA_SITE_KEY_V3,{action:t})54 url = driver.find_element_by_css_selector('[title="recaptcha challenge"]').get_attribute('src')55 site_key = parse_qs(urlparse.urlparse(url).query)['k'][0]56 solver = TwoCaptcha(os.getenv('2CAPTCHA_API_KEY'))57 result = solver.recaptcha(sitekey=site_key, url=driver.current_url)58 driver.execute_script('document.getElementById("g-recaptcha-response").innerHTML="{}";'.format(result['code']))59 driver.find_element_by_css_selector('[class="tv-button__loader"]').click()60 time.sleep(1)61 62 wait_for_presence(driver, By.CSS_SELECTOR, '[class*="js-user-dropdown"]')63 # get to chart page64 driver.get('https://www.tradingview.com/chart/')65 wait_for_presence(driver, By.ID, 'header-toolbar-symbol-search')66 return driver67def get_ticker_chart():68 j = request.json69 logger.info('received /api/gettickerchart post request with request form {}'.format(j))70 api_key = j.get('apikey')71 if not authorize_api_key(api_key):72 logger.info(73 'returned statue code {} to the /api/gettickerchart post request with request form {}'.format(401, j))74 return {'error': 'unauthorized api key'}, 40175 is_success = False76 retries, max_retries = 0, 277 chart = {'chart': -2}, 20078 if mutex.locked():79 send_notification_email(eval(os.getenv('NOTIFICATION_RECEIVER_EMAIL')),80 format_email_message(filename='tradingview_controller.py', message='encountered -2'))81 return chart82 with mutex:83 while not is_success:84 try:85 chart = get_ticker_chart_helper()86 is_success = True87 except Exception as e:88 raise e89 chart = {'chart': -3}, 20090 logger.error(e)91 retries += 192 is_success = retries >= max_retries93 return chart94def get_ticker_chart_helper():95 j = request.json96 global logged_in_driver, last_fetch_time, chart_cache97 ticker = j.get('ticker').strip().upper().replace('!', '!')98 cache_time_factor, cache_time = 1 / 4, 099 # 5 mins - 5, 15 mins - 15, 30 mins - 30100 # 1 hour - 60, 4 hours - 240, 1 day - 1D101 interval = '1D'102 if 'interval' not in j.keys():103 interval = '1D'104 elif int(j.get('interval')) == 5:105 interval = '5'106 elif int(j.get('interval')) == 15:107 interval = '15'108 elif int(j.get('interval')) == 30:109 interval = '30'110 elif int(j.get('interval')) == 1:111 interval = '60'112 elif int(j.get('interval')) == 4:113 interval = '240'114 if interval == '1D':115 cache_time = cache_time_factor * 24 * 60 * 60116 else:117 cache_time = cache_time_factor * int(interval) * 60118 num_of_zoom_in = 9119 pine_script_name = 'AirForce-83'120 # remove expired cache121 expired_keys = [key for key, value in chart_cache.items() if get_est_time().timestamp() >= value['expiration']]122 for key in expired_keys:123 del chart_cache[key]124 # if there is a recent search within 5 hours in cache, return from the cache125 for value in chart_cache.values():126 if value['ticker'] == ticker and value['interval'] == interval:127 logger.info(128 'returned statue code {} to the /api/gettickerchart post request with request form {}'.format(200, j))129 return {'chart': value['chart']}, 200130 # if driver never logged in131 if logged_in_driver is None or driver_has_quit(logged_in_driver):132 logged_in_driver = log_in()133 # if last fetch time is previous day, re-login and reset cache134 if (get_est_time() - last_fetch_time).days >= 1:135 logged_in_driver.quit()136 logged_in_driver = log_in()137 chart_cache = {}138 # if log in session expires139 if not element_exists(logged_in_driver, By.CSS_SELECTOR, '[class*="sources"]') \140 or (element_exists(logged_in_driver, By.CSS_SELECTOR, '[class*="sources"]')141 and pine_script_name not in logged_in_driver.find_element_by_css_selector('[class*="sources"]').text):142 logged_in_driver.quit()143 logged_in_driver = None144 raise Exception()145 last_fetch_time = get_est_time()146 driver = logged_in_driver147 # search ticker148 wait_for_presence(driver, By.ID, 'header-toolbar-symbol-search')149 driver.find_element_by_id('header-toolbar-symbol-search').click()150 wait_for_presence(driver, By.CSS_SELECTOR, '[data-role="search"]')151 driver.find_element_by_css_selector('[data-role="search"]').send_keys(ticker)152 wait_for_presence(driver, By.CSS_SELECTOR, '[class*="listContainer"]')153 # check if ticker exists, if not, return -1154 try:155 wait_for_text_presence(driver, By.CSS_SELECTOR, '[class*="listContainer"]', ticker)156 except Exception as e:157 if 'No symbols match your criteria' in driver.find_element_by_css_selector('[class*="dialog"]').text:158 driver.find_element_by_css_selector('[class*="dialog"]').send_keys(Keys.ESCAPE)159 logger.info(160 'returned statue code {} to the /api/gettickerchart post request with request form {}'.format(200, j))161 return {'chart': -1}, 200162 driver.find_element_by_css_selector('[data-role="search"]').send_keys(Keys.RETURN)163 # select time interval164 time.sleep(1)165 wait_for_presence(driver, By.CSS_SELECTOR, '#header-toolbar-intervals [data-role="button"]')166 driver.find_element_by_css_selector('#header-toolbar-intervals [data-role="button"]').click()167 wait_for_presence(driver, By.CSS_SELECTOR, '[data-value="{}"]'.format(interval))168 driver.find_element_by_css_selector('[data-value="{}"]'.format(interval)).click()169 # select time zone170 time.sleep(1)171 wait_for_presence(driver, By.CSS_SELECTOR, '[data-name="time-zone-menu"]')172 driver.find_element_by_css_selector('[data-name="time-zone-menu"]').click()173 wait_for_presence(driver, By.CSS_SELECTOR, '[data-name="menu-inner"]')174 timezone_elements = driver.find_elements(By.CSS_SELECTOR, '[data-name="menu-inner"] tr')175 est_element = \176 [timezone_element for timezone_element in timezone_elements if 'Toronto' in timezone_element.text][0]177 est_element.click()178 # resize the viewing point179 time.sleep(1)180 driver.find_element_by_tag_name('body').send_keys(Keys.ESCAPE)181 action = webdriver.ActionChains(driver)182 action.move_to_element(driver.find_element_by_css_selector('[class*="control-bar__btn--move-left"]'))183 action.perform()184 driver.find_element_by_css_selector('[class*="control-bar__btn--move-left"]').click()185 wait_for_presence(driver, By.CSS_SELECTOR, '[class*="control-bar__btn--turn-button"]')186 driver.find_element_by_css_selector('[class*="control-bar__btn--turn-button"]').click()187 for i in range(num_of_zoom_in):188 try:189 wait_for_presence(driver, By.CSS_SELECTOR, '[class*="control-bar__btn--zoom-in"]')190 driver.find_element_by_css_selector('[class*="control-bar__btn--zoom-in"]').click()191 except Exception:192 pass193 # close all pop up windows194 pop_up_windows = driver.find_elements(By.CSS_SELECTOR, '[class*="close-button"]')195 for pop_up_window in pop_up_windows:196 pop_up_window.click()197 # move away the mouse from chart198 action = webdriver.ActionChains(driver)199 action.move_to_element(200 driver.find_element_by_css_selector('#drawing-toolbar > div > div > div > div > div:nth-child(6)'))201 action.perform()202 # close pop up windows again203 driver.find_element_by_tag_name('body').send_keys(Keys.ESCAPE)204 time.sleep(1)205 wait_for_presence(driver, By.CSS_SELECTOR, '[class*="chart-container single-visible"]')206 chart = driver.find_element_by_css_selector('[class*="chart-container single-visible"]').screenshot_as_base64207 # update cache with the new chart208 chart_cache[get_est_time().timestamp()] = {'ticker': ticker, 'interval': interval, 'chart': chart,209 'expiration': get_est_time().timestamp() + cache_time}210 logger.info('returned statue code {} to the /api/gettickerchart post request with request form {}'.format(200, j))...

Full Screen

Full Screen

runner.py

Source:runner.py Github

copy

Full Screen

...40 self.server = server41 self.wait_timeout = wait_timeout42 self.pool = ThreadPoolExecutor()43 self.driver = None44 def wait_for_presence(self, loc) -> Any:45 try:46 return WebDriverWait(self.driver, self.wait_timeout)\47 .until(48 expected_conditions.presence_of_element_located(loc))49 except selexcpt.TimeoutException:50 logger.debug('TimeoutException')51 return None52 except Exception as error:53 logger.debug(f'wait_for_presence::Exception: {error}')54 return None55 def get_full_image(self) -> str:56 ret = ""57 try:58 e = self.wait_for_presence(59 (AppiumBy.ID, 'com.whatsapp:id/picture_animation'))60 if not e:61 raise Exception('Picture Animation not found')62 logger.debug('Taking a screenshot')63 ib = b64decode(self.driver.get_screenshot_as_base64())64 logger.debug('Cropping the screenshot')65 r = Image.open(BytesIO(ib)).crop((66 e.location['x'],67 e.location['y'],68 e.location['x'] + e.size['width'],69 e.location['y'] + e.size['height']))70 logger.debug('Decoding to b64')71 buffer = BytesIO()72 r.save(buffer, format="png")73 ret = b64encode(buffer.getvalue()).decode()74 except Exception as error:75 logger.error(f'Exception getting image: {error}')76 finally:77 return ret78 def get_text(self, id: str) -> str:79 e = self.wait_for_presence((AppiumBy.ID, id))80 return e.text if e else ""81 def click(self, id: str) -> None:82 e = self.wait_for_presence((AppiumBy.ID, id))83 if e:84 e.click()85 def execute(self, req: Request) -> None:86 with AppiumConnection(self.server) as driver:87 self.driver = driver88 self.execute_conn(req)89 def execute_conn(self, req: Request) -> None:90 number: str = req.target91 ci: dict = {92 'contact_title': '',93 'contact_subtitle': '',94 'contact_status': '',95 'contact_status_info': '',96 'contact_image': ''97 }98 logger.debug('Opening new chat')99 self.driver.execute_script(100 'mobile: shell', {101 'command': 'am',102 'args': 'start -a android.intent.action.VIEW '103 f'-d "https://api.whatsapp.com/send?phone={number}"'}104 )105 logger.debug('Looking for contact name')106 self.click('com.whatsapp:id/conversation_contact_name')107 logger.debug('Looking for contact title')108 ci['contact_title'] = self.get_text('com.whatsapp:id/contact_title')109 logger.debug('Looking for contact subtitle')110 ci['contact_subtitle'] = \111 self.get_text('com.whatsapp:id/contact_subtitle')112 logger.debug('Looking for contact status')113 ci['contact_status'] = self.get_text('com.whatsapp:id/status')114 print('Looking for contact status info')115 ci['contact_status_info'] = \116 self.get_text('com.whatsapp:id/status_info')117 logger.debug('Looking for contact image')118 self.click('com.whatsapp:id/profile_picture_image')119 ci['contact_image'] = self.get_full_image()120 # logger.debug('Navigating to up steps')121 # bt = self.wait_for_presence(122 # (AppiumBy.ACCESSIBILITY_ID, 'Navigate up'))123 # if bt:124 # bt.click()125 d = 'Ok with any info' if any(ci.values()) else \126 'Target is not sharing any info'127 req.answer(Response(ResponseStatus.OK, d, *ci.values()))128 async def run(self):129 while True:130 logger.debug('waiting for request')131 req: Request = await self.req_queue.get()132 if not req.answered():133 logger.debug('New request, found, executing...')134 try:135 loop = get_running_loop()...

Full Screen

Full Screen

Register_page.py

Source:Register_page.py Github

copy

Full Screen

...24 def get_mr(self):25 return Utils.wait_to_be_clickable(self.driver, self.mr, 30)26 27 def get_first_name(self):28 return Utils.wait_for_presence(self.driver, self.first_name, 30)29 30 def get_last_name(self):31 return Utils.wait_for_presence(self.driver, self.last_name, 30)32 33 def get_password(self):34 return Utils.wait_for_presence(self.driver, self.password, 30)35 36 def get_addesss(self):37 return Utils.wait_for_presence(self.driver, self.address, 30)38 39 def get_city(self):40 return Utils.wait_for_presence(self.driver, self.city, 30)4142 def get_state(self):43 return Select(Utils.wait_for_presence(self.driver, self.state, 30))44 45 def get_zip_code(self):46 return Utils.wait_for_presence(self.driver, self.zip_code, 30)47 48 def get_phone(self):49 return Utils.wait_for_presence(self.driver, self.phone, 30)5051 def get_register_btn(self):52 return Utils.wait_to_be_clickable(self.driver, self.register_btn, 30)53 54 def get_register_form(self): ...

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 pom automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful