def capture_screenshot(driver: webdriver, title: str): """ This method captures screenshot and copied it at given location. """ try: log = customLogger(logging.INFO) log.info("Capturing the screen shot of failed test case '" + title + "'.") # Get path of screen shot folder paths = GetPath() os = GenericFunctions.get_os() screenshot_folder = paths.screenshot_folder_path() # create screenshot name using title and timestamp # current_date = "_".join(re.split(" |\:|\.", str(GenericFunctions.get_current_date_time()))) current_date = GenericFunctions.get_filename_datetimestamp() if os.casefold() == 'windows': screenshot_name = "\\" + title + "_" + current_date + ".png" else: screenshot_name = "/" + title + "_" + current_date + ".png" screenshot_path = screenshot_folder + screenshot_name log.info("Screenshot path: " + screenshot_path) if driver is not None: driver.save_screenshot(screenshot_path) else: log.error("Driver is None ") except Exception as e: log.error("Capture Screenshot exception: " + str(e)) return screenshot_path
def execSearch(browser: webdriver, URL): """ Googleで検索を実行する :param browser: webdriver """ # スクリーンショットのファイル名用に日付を取得 dt = datetime.datetime.today() dtstr = dt.strftime("%Y%m%d%H%M%S") # Googleにアクセス # スクショしたい画面を表示 browser.get(URL) sleep(1) # # キーワードの入力 # search_box = browser.find_element_by_name("q") # search_box.send_keys('docker selenium') # # 検索実行 # search_box.submit() sleep(1) # 画面全体をスクショするための調整 w = browser.execute_script('return document.body.scrollWidth') h = browser.execute_script('return document.body.scrollHeight') browser.set_window_size(w, h) # スクリーンショット browser.save_screenshot('images/' + dtstr + '.png')
def navigateLogin(driver: webdriver) -> HtmlChecker: driver.save_screenshot("Post_Login.png") resultBtn = driver.find_element_by_xpath("//a[@data-id='21']") resultBtn.click() time.sleep(10) driver.save_screenshot("Results.png") pageSource = driver.page_source HtmlObj = HtmlChecker(pageSource) driver.quit() return HtmlObj
def save_screenshot(driver: webdriver, sub_filename, element, describe=None): """ 用途:对当前屏幕截图并保存到当前路径,同时标记被操作的元素为高亮,图片文件名格式为:当前时间+sub_filename.png :param driver: webdriver :param sub_filename: 文件的部分名称,为了区分建议用selector命名 :param element: 需要被高亮的元素 :param describe: 方法的描述,同时也作为png图片文件名的一部分 :return: """ name = os.path.abspath('screenshot') + '/' # name = "C:/Users/Administrator/PycharmProjects/haige_selenium/screenshot/" st = strftime("%Y-%m-%d-%H-%M-%S", localtime(time())) file_name = name + st + '-' + sub_filename + describe + ".png" height_lig(driver, element) driver.save_screenshot(file_name)
def execSearch(assignBrowser: webdriver): dateString = datetime.datetime.today().strftime("%Y%m%d%H%M%S") # Open the browser with assign URL assignBrowser.get('https://google.com') # Input keyword in search field search_box = assignBrowser.find_element_by_name("q") search_box.send_keys('WilliamTai.moe') # Submit search search_box.submit() # Take screenshot and save to local disk assignBrowser.save_screenshot('./tmp/selenium_screenshot/' + dateString + '.png')
def vote(browser: webdriver): # スクリーンショットのファイル名用に日付を取得 dt = datetime.datetime.today() dtstr = dt.strftime("%Y%m%d%H%M%S") # ページアクセス browser.get('https://aoyama.missportal.jp/mr/06/') sleep(3) # 投票 vote_button = browser.find_element_by_id('submit-btn') vote_button.click() sleep(3) # スクショ browser.save_screenshot('images/' + dtstr + '.png')
def scrollAndScreenshotElement(_driver: webdriver, _element: WebElement, _id): if _element.is_enabled(): imgutils.scroll_to_top_of_page_with_JS(_driver) y_scroll_value = _element.location.get('y') imgutils.scroll_to_Coordinate_Y(_driver, y_scroll_value - 30) file_path = r'.\\screenshots\\' #print("Saving screenshot to: " + file_path + "screenshot_" + str(_id) + ".png") _driver.save_screenshot(file_path + "screenshot_" + str(_id) + ".png") imgutils.unhighlight_element(_driver, _element) return (file_path + "screenshot_" + str(_id) + ".png") # TODO: imprint the image location on the file '''
def execSearch(browser: webdriver): """ Googleで検索を実行する :param browser: webdriver """ # スクリーンショットのファイル名用に日付を取得 dt = datetime.datetime.today() dtstr = dt.strftime("%Y%m%d%H%M%S") # Googleにアクセス browser.get('https://www.google.co.jp/') sleep(1) # キーワードの入力 browser.find_element_by_id('lst-ib').send_keys('docker selenium') # 検索実行 browser.find_element_by_name('btnK').submit() sleep(1) # スクリーンショット browser.save_screenshot('images/' + dtstr + '.png')
def save_screenshot(driver: webdriver, info_text: str, bookmaker_matchid: str): screen_order = 1 for punct in punctuation: info_text = info_text.replace(punct, '_') info_text = info_text.replace(' ', '_') info_text = info_text.replace('\n', '_') while info_text.find('__') >= 0: info_text = info_text.replace('__', '_') screen_filename = f'screens/{bookmaker_matchid}-{info_text}-{screen_order}.png' while os.path.isfile(screen_filename): screen_order = screen_order + 1 screen_filename = f'screens/{bookmaker_matchid}-{info_text}-{screen_order}.png' try: logging.debug(f'Saving screenshot {screen_filename}') driver.save_screenshot(screen_filename) except TimeoutException: logging.error( f'Timeout while saving screenshot in match {bookmaker_matchid}. Original error message text: {info_text}' ) except Exception: logging.exception( f'Error while saving screenshot in match {bookmaker_matchid}. Original error message text: {info_text}' )
def sacar_foto_elemento(navegador: webdriver, xpath, fichero): # Buscamos el elemento elemento = navegador.find_element_by_xpath(xpath) # Nos aseguramos que queda visible y pedimos la posicion posicion = elemento.location_once_scrolled_into_view # Y pedimos su tamaño tamano = elemento.size # Sacamos una foto de la pagina completa navegador.save_screenshot(fichero) # Calculamos las coordenadas donde debemos cortar x = posicion['x'] y = posicion['y'] width = posicion['x'] + tamano['width'] height = posicion['y'] + tamano['height'] # Y cortamos im = Image.open(fichero) im = im.crop((int(x), int(y), int(width), int(height))) im.save(fichero)
def cita_selection(driver: webdriver, context: CustomerProfile): resp_text = body_text(driver) if "Por favor, valide el Captcha para poder continuar" in resp_text: success = process_captcha(driver, context, partially=True) if not success: return None return phone_mail(driver, context, retry=True) elif "DISPONE DE 5 MINUTOS" in resp_text: logging.info("Cita attempt -> selection hit! :)") if context.save_artifacts: driver.save_screenshot(f"citas-{datetime.datetime.now()}.png".replace(":", "-")) try: driver.find_elements_by_css_selector("input[type='radio'][name='rdbCita']")[ 0 ].send_keys(Keys.SPACE) except Exception as e: logging.error(e) pass driver.execute_script("envia();") time.sleep(0.5) driver.switch_to.alert.accept() elif "Seleccione una de las siguientes citas disponibles" in resp_text: logging.info("Cita attempt -> selection hit! :)") if context.save_artifacts: driver.save_screenshot(f"citas-{datetime.datetime.now()}.png".replace(":", "-")) try: slots = driver.find_elements_by_css_selector("#CitaMAP_HORAS tbody [id^=HUECO]") slot_ids = sorted([*map(lambda x: x.get_attribute("id"), slots)]) if slot_ids: slot = slot_ids[0] driver.execute_script(f"confirmarHueco({{id: '{slot}'}}, {slot[5:]});") driver.switch_to.alert.accept() except Exception as e: logging.error(e) return None else: logging.info("Cita attempt -> missed selection :(") return None # 8. Confirmation resp_text = body_text(driver) if "Debe confirmar los datos de la cita asignada" in resp_text: logging.info("Cita attempt -> confirmation hit! :)") if context.telegram_token: dispatcher = context.updater.dispatcher def shutdown(): context.updater.stop() context.updater.is_idle = False def code_received(update, ctx): logging.info(f"Received code: {ctx.args[0]}") element = driver.find_element_by_id("txtCodigoVerificacion") element.send_keys(ctx.args[0]) driver.find_element_by_id("chkTotal").send_keys(Keys.SPACE) driver.find_element_by_id("enviarCorreo").send_keys(Keys.SPACE) btn = driver.find_element_by_id("btnConfirmar") btn.send_keys(Keys.ENTER) resp_text = body_text(driver) ctime = datetime.datetime.now() if "CITA CONFIRMADA Y GRABADA" in resp_text: context.bot_result = True code = driver.find_element_by_id("justificanteFinal").text logging.info(f"Justificante cita: {code}") caption = f"Cita confirmed! {code}" if context.save_artifacts: image_name = f"CONFIRMED-CITA-{ctime}.png".replace(":", "-") driver.save_screenshot(image_name) ctx.bot.send_photo( chat_id=update.effective_chat.id, photo=open(os.path.join(os.getcwd(), image_name), "rb"), caption=caption, ) btn = driver.find_element_by_id("btnImprimir") btn.send_keys(Keys.ENTER) else: ctx.bot.send_message(chat_id=update.effective_chat.id, text=caption) threading.Thread(target=shutdown).start() return True elif "Lo sentimos, el código introducido no es correcto" in resp_text: ctx.bot.send_message( chat_id=update.effective_chat.id, text="Incorrect, please try again" ) else: error_name = f"error-{ctime}.png".replace(":", "-") driver.save_screenshot(error_name) ctx.bot.send_photo( chat_id=update.effective_chat.id, photo=open(os.path.join(os.getcwd(), error_name), "rb"), ) ctx.bot.send_message( chat_id=update.effective_chat.id, text="Something went wrong" ) dispatcher.add_handler(CommandHandler("code", code_received, pass_args=True)) context.updater.start_polling(poll_interval=1.0) for i in range(5): speaker.say("ALARM") # Waiting for response 5 minutes time.sleep(360) threading.Thread(target=shutdown).start() if context.save_artifacts: driver.save_screenshot( f"FINAL-SCREEN-{datetime.datetime.now()}.png".replace(":", "-") ) if context.bot_result: driver.quit() os._exit(0) return None else: for i in range(10): speaker.say("ALARM") logging.info("Press Any button to CLOSE browser") input() driver.quit() os._exit(0) else: logging.info("Cita attempt -> missed confirmation :(") if context.save_artifacts: driver.save_screenshot( f"failed-confirmation-{datetime.datetime.now()}.png".replace(":", "-") ) return None
def saveScreenShot(wedriver: webdriver, fileName): wedriver.save_screenshot(fileName)
def cita_selection(driver: webdriver, context: CustomerProfile): try: WebDriverWait(driver, DELAY).until( EC.presence_of_element_located((By.TAG_NAME, "body"))) except TimeoutException: logging.error("Timed out waiting for body to load") return None resp_text = driver.find_element_by_tag_name("body").text if "DISPONE DE 5 MINUTOS" in resp_text: logging.info("Cita attempt -> selection hit! :)") if context.save_artifacts: driver.save_screenshot( f"citas-{datetime.datetime.now()}.png".replace(":", "-")) try: driver.find_elements_by_css_selector( "input[type='radio'][name='rdbCita']")[0].send_keys(Keys.SPACE) except Exception as e: logging.error(e) pass btn = driver.find_element_by_id("btnSiguiente") btn.send_keys(Keys.ENTER) driver.switch_to.alert.accept() else: logging.info("Cita attempt -> missed selection :(") return None # 9. Confirmation try: WebDriverWait(driver, DELAY).until( EC.presence_of_element_located((By.TAG_NAME, "body"))) except TimeoutException: logging.error("Timed out waiting for body to load") return None resp_text = driver.find_element_by_tag_name("body").text if "Debe confirmar los datos de la cita asignada" in resp_text: logging.info("Cita attempt -> confirmation hit! :)") if context.telegram_token: dispatcher = context.updater.dispatcher def shutdown(): context.updater.stop() context.updater.is_idle = False def code_received(update, ctx): logging.info(f"Received code: {ctx.args[0]}") element = driver.find_element_by_id("txtCodigoVerificacion") element.send_keys(ctx.args[0]) driver.find_element_by_id("chkTotal").send_keys(Keys.SPACE) driver.find_element_by_id("enviarCorreo").send_keys(Keys.SPACE) btn = driver.find_element_by_id("btnConfirmar") btn.send_keys(Keys.ENTER) try: WebDriverWait(driver, DELAY).until( EC.presence_of_element_located((By.TAG_NAME, "body"))) except TimeoutException: logging.info("Timed out waiting for body to load") return None resp_text = driver.find_element_by_tag_name("body").text ctime = datetime.datetime.now() if "CITA CONFIRMADA Y GRABADA" in resp_text: context.bot_result = True code = driver.find_element_by_id("justificanteFinal").text logging.info(f"Justificante cita: {code}") caption = f"Cita confirmed! {code}" if context.save_artifacts: image_name = f"CONFIRMED-CITA-{ctime}.png".replace( ":", "-") driver.save_screenshot(image_name) ctx.bot.send_photo( chat_id=update.effective_chat.id, photo=open(os.path.join(os.getcwd(), image_name), "rb"), caption=caption, ) btn = driver.find_element_by_id("btnImprimir") btn.send_keys(Keys.ENTER) else: ctx.bot.send_message(chat_id=update.effective_chat.id, text=caption) threading.Thread(target=shutdown).start() return True elif "Lo sentimos, el código introducido no es correcto" in resp_text: ctx.bot.send_message(chat_id=update.effective_chat.id, text="Incorrect, please try again") else: error_name = f"error-{ctime}.png".replace(":", "-") driver.save_screenshot(error_name) ctx.bot.send_photo( chat_id=update.effective_chat.id, photo=open(os.path.join(os.getcwd(), error_name), "rb"), ) ctx.bot.send_message(chat_id=update.effective_chat.id, text="Something went wrong") dispatcher.add_handler( CommandHandler("code", code_received, pass_args=True)) context.updater.start_polling(poll_interval=1.0) for i in range(5): speaker.say("ALARM") # Waiting for response 5 minutes time.sleep(360) threading.Thread(target=shutdown).start() if context.save_artifacts: driver.save_screenshot( f"FINAL-SCREEN-{datetime.datetime.now()}.png".replace( ":", "-")) if context.bot_result: driver.quit() os._exit(0) return None else: for i in range(5): speaker.say("ALARM") logging.info("Press Any button to CLOSE browser") input() else: logging.info("Cita attempt -> missed confirmation :(") if context.save_artifacts: driver.save_screenshot( f"failed-confirmation-{datetime.datetime.now()}.png".replace( ":", "-")) return None