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 verificar_elemento_html_por_id(html_id: str, web_driver: WebDriver): try: web_driver.find_element_by_id(html_id) return True except NoSuchElementException: return False
def _test_image_transform( self, driver: WebDriver, image_holder: WebElement, left_transform_matrices: List[Tuple[str, str]], right_transform_matrices: List[Tuple[str, str]], ) -> None: main_image_container = driver.find_element_by_id( 'id_main_image_container', ) rotate_left_elem = driver.find_element_by_id('id_rotate_left') for rotation_matrix, translation_matrix in left_transform_matrices: rotate_left_elem.click() transform = image_holder.value_of_css_property('transform') self.assertEqual(rotation_matrix, transform) drag_image = ActionChains(driver) drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=57, yoffset=91, ) drag_image.click_and_hold() drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=107, yoffset=191, ) drag_image.release() drag_image.perform() transform = image_holder.value_of_css_property('transform') self.assertEqual(translation_matrix, transform) rotate_left_elem.click() rotate_right_elem = driver.find_element_by_id('id_rotate_right') for rotation_matrix, translation_matrix in right_transform_matrices: rotate_right_elem.click() transform = image_holder.value_of_css_property('transform') self.assertEqual(rotation_matrix, transform) drag_image = ActionChains(driver) drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=57, yoffset=91, ) drag_image.click_and_hold() drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=107, yoffset=191, ) drag_image.release() drag_image.perform() transform = image_holder.value_of_css_property('transform') self.assertEqual(translation_matrix, transform) rotate_right_elem.click()
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 test_password_update_ok(selenium: WebDriver) -> None: user_infos = register_valid_user(selenium) menus = selenium.find_elements_by_class_name('menu') menus[2].click() login_valid_user(selenium, user_infos) # click on user name menus = selenium.find_elements_by_class_name('menu') menus[0].click() # click on 'Change password' submit_button = selenium.find_element_by_tag_name('button') submit_button.click() # update password new_password = '******' password = selenium.find_element_by_id('oldPassword') password.send_keys(user_infos.get('password')) password = selenium.find_element_by_id('password') password.send_keys(new_password) password_conf = selenium.find_element_by_id('confirm-password') password_conf.send_keys(new_password) submit_button = selenium.find_element_by_tag_name('button') submit_button.click() # log out menus = selenium.find_elements_by_class_name('menu') menus[2].click() # log in user_infos['password'] = user_infos['password_conf'] = new_password login_valid_user(selenium, user_infos)
def get_job_tran_run_id(browser: WebDriver, tran_name: str, submitter_input: str) -> str: console = browser.find_element_by_link_text('CDS Console') console.click() Transactionname = browser.find_element_by_css_selector('input[id = "Filters_TranName"]') Transactionname.send_keys(tran_name) submitter = browser.find_element_by_id('Filters_Submitter') submitter.clear() submitter = browser.find_element_by_id('Filters_Submitter') submitter.send_keys(submitter_input) show = browser.find_element_by_id('Filters_Timefilterval') show.send_keys('All') Apply_Filter = browser.find_element_by_id('ApplyFilterButton') Apply_Filter.click() rows = browser.find_elements_by_css_selector('tr.table_row') for row in rows: cells = row.find_elements_by_tag_name('td') for i, c in enumerate(cells): if c.text == tran_name: tran_run_id = cells[i + 10].text return tran_run_id
def _login(self, driver: WebDriver) -> bool: # https://stackoverflow.com/a/27417860/706389 BT_TIMEOUT = 5 # seconds driver.implicitly_wait(BT_TIMEOUT) driver.set_page_load_timeout(BT_TIMEOUT) BT_PAGE = "https://www.btopenzone.com:8443/home" driver.get(BT_PAGE) # TODO huh, on VPN it shows 'you may have lost connection'. weird. if "You’re now logged in to BT Wi-fi" in driver.page_source: self.logger.warning("Already logged... weird, doing nothing") return True # this is the weird bug 'wifi access has expired' if len(driver.find_elements_by_link_text("Buy more time")) > 0: driver.find_element_by_link_text("Logout").click() # TODO how to wait? # select 'BT Wi-fi driver.find_element_by_id("provider2").click() # for some reason every bt wifi option (FON/Broadband/Wifi) has its own form # so we have to find the one responsible for BT WiFI login login_form = driver.find_element_by_id('wifi_logon_form') login_form.find_element_by_id("username").send_keys(self.username) login_form.find_element_by_id("password").send_keys(self.password) login_form.find_element_by_id("loginbtn").click() return True
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 scrape_product(driver: WebDriver) -> Dict: """Scrape a product page. :param driver: selenium web driver """ price = None deal_price = None rrp = None product_title = driver.find_element_by_id("productTitle").text availability = driver.find_element_by_id("availability").text try: price = driver.find_element_by_id("priceblock_ourprice").text except NoSuchElementException: deal_price = driver.find_element_by_id("priceblock_dealprice").text rrp = driver.find_element_by_class_name( "priceBlockStrikePriceString").text return { "Product Name": product_title, "Product Price": price, "Product Deal": deal_price, "Product RRP": rrp, "Product Availability": availability, "Date": datetime.datetime.now(), }
def _join_game(self, driver: WebDriver, join_url: str) -> None: driver.get(join_url) self.assertEqual('Join Game', driver.title) name_elem = driver.find_element_by_id('id_name') name_elem.send_keys('Test Player') submit_elem = driver.find_element_by_id('id_submit') submit_elem.click() self.assertEqual('Play', driver.title)
def verificar_display_flex_modal_mensaje_de_exito(web_driver: WebDriver): try: modal_de_exito = web_driver.find_element_by_id('notification') display = modal_de_exito.value_of_css_property('display') while display == 'flex': modal_de_exito = web_driver.find_element_by_id('notification') display = modal_de_exito.value_of_css_property('display') except NoSuchElementException: pass
def find_lesson( driver: WebDriver, studio: str, schedule: datetime, return_element: bool = False ) -> Union[Optional[Lesson], Tuple[Optional[Lesson], Optional[WebElement]]]: if not is_login(driver): raise NotLoginError() driver.get(RESERVE_URL) select_studio(driver, studio) for _ in range(3): for div in driver.find_elements_by_tag_name('div'): if div.get_attribute('id') not in ('day_', 'day__b'): continue lesson_date =\ div.find_element_by_tag_name('div').text.split('(')[0] dt = convert_datetime(lesson_date, clock=None) if schedule.date() != dt.date(): continue valid_units = ['unit', 'unit_past', 'unit_reserved'] lesson_elements = sum([div.find_elements_by_class_name(unit) for unit in valid_units], []) for lesson_element in lesson_elements: contents = lesson_element.find_elements_by_tag_name('p') start_time = contents[0].text.split('~')[0] dt = convert_datetime(lesson_date, clock=start_time) if abs(schedule - dt) > timedelta(minutes=1): continue program = contents[1].text instructor = contents[2].text unit = lesson_element.get_attribute('class') current_time = datetime.now() if current_time < schedule and unit == 'unit_past': unit = 'unit_full' status = { 'unit': Reservation.VACANT, 'unit_full': Reservation.FULL, 'unit_past': Reservation.PAST, 'unit_reserved': Reservation.RESERVED, }[unit] lesson = Lesson(schedule=schedule, studio=studio, program=program, instructor=instructor, status=status) logger.info(lesson.json()) return (lesson, lesson_element) if return_element else lesson driver.find_element_by_id('week') \ .find_elements_by_tag_name('a')[1].click() return_values = (None, None) if return_element else None return return_values
def fill_form(selenium: WebDriver, form_values: Dict, is_category: bool = True) -> None: name = selenium.find_element_by_id('name') name.clear() name.send_keys(form_values['name']) if is_category: description = selenium.find_element_by_id('description') description.clear() description.send_keys(form_values['description']) submit_button = selenium.find_element_by_tag_name('button') submit_button.click()
def find_login_inputs( driver: WebDriver) -> Tuple[WebElement, WebElement, WebElement]: """ Helper method to retrieve email input, password input and submit button in the login form. :param driver: webdriver instance :return: email_input, password_input, submit_button """ email_input = driver.find_element_by_id("email") password_input = driver.find_element_by_id("password") submit_button = driver.find_element_by_id("loginbtn") return email_input, password_input, submit_button
def _test_zoom( self, driver: WebDriver, image_holder: WebElement, ) -> None: zoom_in_elem = driver.find_element_by_id('id_zoom_in') zoom_in_transforms = ( 'matrix(1.5, 0, 0, 1.5, 0, 0)', 'matrix(2.25, 0, 0, 2.25, 0, 0)', 'matrix(3.375, 0, 0, 3.375, 0, 0)', 'matrix(5.0625, 0, 0, 5.0625, 0, 0)', 'matrix(7.59375, 0, 0, 7.59375, 0, 0)', 'matrix(11.3906, 0, 0, 11.3906, 0, 0)', 'matrix(17.0859, 0, 0, 17.0859, 0, 0)', 'matrix(25.6289, 0, 0, 25.6289, 0, 0)', 'matrix(38.4434, 0, 0, 38.4434, 0, 0)', 'matrix(38.4434, 0, 0, 38.4434, 0, 0)', ) for zoom_in_transform in zoom_in_transforms: zoom_in_elem.click() transform = image_holder.value_of_css_property('transform') self.assertEqual(zoom_in_transform, transform) zoom_out_elem = driver.find_element_by_id('id_zoom_out') zoom_out_transforms = ( 'matrix(25.6289, 0, 0, 25.6289, 0, 0)', 'matrix(17.0859, 0, 0, 17.0859, 0, 0)', 'matrix(11.3906, 0, 0, 11.3906, 0, 0)', 'matrix(7.59375, 0, 0, 7.59375, 0, 0)', 'matrix(5.0625, 0, 0, 5.0625, 0, 0)', 'matrix(3.375, 0, 0, 3.375, 0, 0)', 'matrix(2.25, 0, 0, 2.25, 0, 0)', 'matrix(1.5, 0, 0, 1.5, 0, 0)', 'matrix(1, 0, 0, 1, 0, 0)', 'matrix(0.666667, 0, 0, 0.666667, 0, 0)', 'matrix(0.444444, 0, 0, 0.444444, 0, 0)', 'matrix(0.296296, 0, 0, 0.296296, 0, 0)', 'matrix(0.197531, 0, 0, 0.197531, 0, 0)', 'matrix(0.131687, 0, 0, 0.131687, 0, 0)', 'matrix(0.0877915, 0, 0, 0.0877915, 0, 0)', 'matrix(0.0877915, 0, 0, 0.0877915, 0, 0)', ) for zoom_out_transform in zoom_out_transforms: zoom_out_elem.click() transform = image_holder.value_of_css_property('transform') self.assertEqual(zoom_out_transform, transform) for _ in range(6): zoom_in_elem.click() transform = image_holder.value_of_css_property('transform') self.assertEqual('matrix(1, 0, 0, 1, 0, 0)', transform)
def verificar_elemento_html_hasta_no_existir_en_el_dom_html( web_driver: WebDriver, time=5, id=None, xpath=None, link_text=None, partial_link_text=None, name=None, tag_name=None, class_name=None, css_selector=None): msg_selector_html_a_localizar = HtmlActions.generar_identificador_excepcion( id, xpath, link_text, partial_link_text, name, tag_name, class_name, css_selector) tiempo_inicial = Temporizador.obtener_tiempo_timer() while True: try: if id is not None: web_driver.find_element_by_id(id) elif xpath is not None: web_driver.find_element_by_xpath(xpath) elif link_text is not None: web_driver.find_element_by_link_text(link_text) elif partial_link_text is not None: web_driver.find_element_by_partial_link_text( partial_link_text) elif name is not None: web_driver.find_element_by_name(name) elif tag_name is not None: web_driver.find_element_by_tag_name(tag_name) elif class_name is not None: web_driver.find_element_by_class_name(class_name) elif css_selector is not None: web_driver.find_element_by_css_selector(css_selector) segundos_transcurridos = Temporizador.obtener_tiempo_timer( ) - tiempo_inicial if segundos_transcurridos > time: e = TimeoutException() e.msg = webdriver_actions_constantes.WEBDRIVER_WAIT_UNTIL_NOT_TIMEOUT_EXCEPTION.format( time, msg_selector_html_a_localizar, e.msg) raise e else: pass except NoSuchElementException: break
def test_can_autentificate_user(selenium: WebDriver): selenium.get(base_url) sign_in_elem = selenium.find_element_by_id("SignInButton") sign_in_elem.click() username_elem = selenium.find_element_by_name("username") username_elem.send_keys("chifir") password_elem = selenium.find_element_by_name("password") password_elem.send_keys("thispasswordistooshort") submit_elem = selenium.find_element_by_id("SubmitLoginButton") submit_elem.click() assert selenium.current_url == base_url
def login_click_bt(driver: WebDriver, username: str, password: str): if "You’re now logged in to BT Wi-fi" in driver.page_source: logger.warning("Already logged... weird, doing nothing") return True # this is the weird bug 'wifi access has expired' if len(driver.find_elements_by_link_text("Buy more time")) > 0: driver.find_element_by_link_text("Logout").click() # TODO how to wait? driver.find_element_by_id("username").send_keys(username) driver.find_element_by_id("password-password").send_keys(password) driver.find_element_by_class_name("lgnbtn").click() return True
def get_options_internal(self, driver: WebDriver, timeout: int): select_gs = driver.find_element_by_id("sg") # Grid Sizes gs_options = { option.get_attribute("value"): option.text for option in select_gs.find_elements_by_tag_name("option") } select_d = driver.find_element_by_id("sd") # Difficulty d_options = { option.get_attribute("value"): option.text for option in select_d.find_elements_by_tag_name("option") } return [("Grid Size", gs_options), ("Difficulty", d_options)]
def test_cant_autentificate_wrong_user(selenium: WebDriver): selenium.get(base_url) sign_in_elem = selenium.find_element_by_id("SignInButton") sign_in_elem.click() username_elem = selenium.find_element_by_name("username") username_elem.send_keys("chifir") password_elem = selenium.find_element_by_name("password") password_elem.send_keys("chifir") submit_elem = selenium.find_element_by_id("SubmitLoginButton") submit_elem.click() error_elem = selenium.find_element_by_name("MessageParagraph") assert error_elem.text == "Incorrect username or password"
def _connect(driver: WebDriver, creds: Credentials): LOGGER.debug('Connecting to lemonde.fr') driver.get('https://journal.lemonde.fr') elements = driver.find_elements_by_class_name('access-login') elements[0].click() mail_input = driver.find_element_by_id('connection_mail') mail_input.send_keys(creds.mail) password_input = driver.find_element_by_id('connection_password') password_input.send_keys(creds.password) connect_button = driver.find_element_by_id('connection_save') connect_button.click()
def _create_game(self, driver: WebDriver) -> str: driver.get('http://coverage:8000/games/create/') name_elem = driver.find_element_by_id('id_name') name_elem.send_keys('Test Admin') guess_elem = driver.find_element_by_id('id_total_time_to_guess') guess_elem.send_keys('30') randomize_elem = driver.find_element_by_id( 'id_should_randomize_fields') randomize_elem.click() randomize_elem.click() submit_elem = driver.find_element_by_id('id_submit') submit_elem.click() self.assertEqual('Play', driver.title) assert isinstance(driver.current_url, str) return driver.current_url
def send_keys_to_autocomplete(driver: WebDriver, element_id: str, keys: str): element = driver.find_element_by_id(element_id) element.send_keys(keys) # Tab away from element and wait element.send_keys(Keys.TAB) time.sleep(1)
def upload_ldss_batch(p_browser: WebDriver, upload_files): logger = logging.getLogger('upload_ldss_batch') p_browser.get('https://eit1-i.svcs.hp.com/cds/LoadLdssAsync') ret_file_name = [] for single_file in upload_files: c_dir = os.getcwd() full_path_file = os.path.join(c_dir, LDSS_INPUT, single_file) logger.info('full_path_file %r' % full_path_file) p_browser.find_element_by_css_selector('input[id = "ldssfile"]').send_keys(full_path_file) validation_option = p_browser.find_element_by_css_selector('select[id = "UploadOptionList"]') validation_option.send_keys('Validate Only') upload_button = p_browser.find_element_by_css_selector('input[value = "Upload"]') upload_button.click() time.sleep(5) for repeat in range(9): upload_status = p_browser.find_element_by_id('tbMontor').get_attribute('value') if 'go to CDS Console' in upload_status and 'Load LDSS Successful:' in upload_status: logger.info('[UPLOAD LDSS OK] Upload {} {}.'.format(full_path_file, upload_status)) ret_file_name.append(os.path.split(full_path_file)[-1]) break else: time.sleep(5) logger.info('sleep 5 seconds...') else: logger.info('{} upload failed.'.format(os.path.split(full_path_file)[-1])) print(upload_status) return ret_file_name
def obtener_mensaje_error_plataforma(driver: WebDriver): existe_error = False leyenda_title = driver.title mensaje_error_localizado = '' if leyenda_title is None: leyenda_title = '' if 'Error' in leyenda_title: existe_error = True if ValidacionesHTML.verificar_elemento_encontrado_por_id(driver, 'errMsg'): elemento_mensaje_error = driver.find_element_by_id('errMsg') mensaje_error_localizado = elemento_mensaje_error.get_attribute('innerHTML') existe_error = True elif ValidacionesHTML.verificar_elemento_encontrado_por_xpath(driver, '//body'): elemento_body = driver.find_element_by_xpath('//body') mensaje_error_localizado = elemento_body.get_attribute('innerHTML') if mensaje_error_localizado is None: mensaje_error_localizado = '' if 'NegotiateSecurityContext' in mensaje_error_localizado or \ 'LogonDenied' in mensaje_error_localizado: existe_error = True return mensaje_error_localizado
def login(selenium: WebDriver, user_infos: Dict, redirect_to_url: bool = False) -> None: if redirect_to_url: selenium.get(f'{URL}login') menus = selenium.find_elements_by_class_name('menu') assert "Log in" in menus[1].text menus[1].click() email = selenium.find_element_by_id('email') email.send_keys(user_infos.get('email')) password = selenium.find_element_by_id('password') password.send_keys(user_infos.get('password')) submit_button = selenium.find_element_by_tag_name('button') submit_button.click()
def login(driver: RemoteWebDriver, username: str = None, password: str = None): """ A method that uses Selenium to log in into FERWeb. :param driver: A RemoteWebDriver object representing the webdriver. :param username: A string containing one's FERWeb username. :param password: A string containing one's FERWeb password. :return: Nothing. """ username, password = get_credentials(username, password) driver.get(login_page_url) username_field = driver.find_element_by_id("username") password_field = driver.find_element_by_id("password") submit_button = driver.find_element_by_xpath( "/html/body/div/div/div/div[2]" "/div/form/div[3]/button") username_field.send_keys(username) password_field.send_keys(password) submit_button.click()
def _test_apply_modal( self, brightness_slider: WebElement, contrast_slider: WebElement, driver: WebDriver, image_view_port_elem: WebElement, ) -> None: move_sliders = ActionChains(driver) brightness_slider_size = brightness_slider.size contrast_slider_size = contrast_slider.size move_sliders.move_to_element_with_offset( to_element=brightness_slider, xoffset=brightness_slider_size['width'] - 1, yoffset=brightness_slider_size['height'] / 2, ) move_sliders.click() move_sliders.move_to_element_with_offset( to_element=contrast_slider, xoffset=contrast_slider_size['width'] - 1, yoffset=contrast_slider_size['height'] / 2, ) move_sliders.click() move_sliders.perform() apply_button = driver.find_element_by_id( 'id_apply_image_editor_button', ) apply_button.click() filter_style = image_view_port_elem.value_of_css_property('filter') self.assertEqual('invert(0) contrast(2) brightness(2)', filter_style)
def scrape_studio_lessons( driver: WebDriver, studio: str, start_date: datetime ) -> List[Lesson]: if not is_login(driver): raise NotLoginError() driver.get(RESERVE_URL) select_studio(driver, studio) lessons = [] while True: week_date = driver.find_element_by_id('week') \ .find_element_by_name('setdate') \ .get_attribute('value') week_date = datetime.strptime(week_date, '%Y/%m/%d') if week_date < start_date: break for div in driver.find_elements_by_tag_name('div'): if div.get_attribute('id') not in ('day_', 'day__b'): continue lesson_date =\ div.find_element_by_tag_name('div').text.split('(')[0] lesson_datetime = convert_datetime(lesson_date, clock=None) lesson_elements = div.find_elements_by_class_name('unit_reserved') for lesson_element in lesson_elements: contents = lesson_element.find_elements_by_tag_name('p') start_time = contents[0].text.split('~')[0] lesson_datetime =\ convert_datetime(lesson_date, clock=start_time) program = contents[1].text instructor = contents[2].text lesson = Lesson(schedule=lesson_datetime, studio=studio, program=program, instructor=instructor, status=Reservation.RESERVED) lessons.append(lesson) logger.info(lesson.json()) driver.find_element_by_id('week') \ .find_elements_by_tag_name('a')[0].click() lessons = sorted(lessons, key=lambda lesson: lesson.schedule) return lessons
def test_main_page(browser: WebDriver): browser.get(f'{BASE_URL}') time.sleep(2) # Test that all needed UI elements are there browser.find_element_by_id('get-order-history') browser.find_element_by_id('create-order-button') browser.find_element_by_id('get-order-input') browser.find_element_by_id('get-order-button')
def create_database( driver: WebDriver, database_name: str, license_name: str, ) -> None: # pragma: no cover """ Create a database. """ target_manager_url = 'https://developer.vuforia.com/vui/develop/databases' driver.get(target_manager_url) ten_second_wait = WebDriverWait(driver, 10) add_database_button_id = 'add-dialog-btn' ten_second_wait.until( expected_conditions.presence_of_element_located( (By.ID, add_database_button_id), ), ) ten_second_wait.until( expected_conditions.element_to_be_clickable( (By.ID, add_database_button_id), ), ) add_database_button_element = driver.find_element_by_id( add_database_button_id, ) add_database_button_element.click() try: add_database_button_element.click() except WebDriverException: pass database_name_id = 'database-name' ten_second_wait.until( expected_conditions.presence_of_element_located( (By.ID, database_name_id), ), ) database_name_element = driver.find_element_by_id(database_name_id) database_name_element.send_keys(database_name) cloud_type_radio_element = driver.find_element_by_id('cloud-radio-btn') cloud_type_radio_element.click() license_dropdown_element = Select( driver.find_element_by_id('cloud-license-dropdown', ), ) time.sleep(1) license_dropdown_element.select_by_visible_text(text=license_name) create_button = driver.find_element_by_id('create-btn') create_button.click()
def run_with(self, driver: WebDriver) -> None: print("Browsing to Amazon Fresh website...") driver.get(URL_AMAZON) print("Browser version: ") print(str(driver.capabilities["version"])) print("Verifying account logged in...") if not driver.find_element_by_xpath(XPATH_HELLO_USER).text.startswith( HELLO): with wx.MessageBox( "Firefox automation profile not logged into Amazon... exiting.", "Amazon Fresh", wx.OK | wx.ICON_ERROR) as dlg: dlg.ShowModal() return print("Opening Amazon Fresh cart...") driver.find_element_by_id(ID_CART).click() driver.find_element_by_xpath(XPATH_CHECKOUT_FRESH_CART).click() continue_buttons = driver.find_elements_by_name( NAME_PROCEED_TO_CHECKOUT) if continue_buttons: continue_buttons[0].click() print("Waiting for delivery time to be available...") num_tries = 0 while not self.killed: for availability in driver.find_elements_by_class_name( CLASSNAME_AVAILABILITY): if NOT_AVAILABLE != availability.text: with HyperlinkDialog("Checkout time available!", title="Amazon Fresh", label="Open Amazon Fresh cart", url=URL_FRESH_CART, style=wx.DEFAULT_DIALOG_STYLE | wx.STAY_ON_TOP) as dlg: dlg.ShowModal() self.killed = True break if self.killed: break num_tries += 1 if num_tries % 5 == 0: print(f" Checked {num_tries} times.") sleep(15) if self.killed: break driver.refresh()
def verificar_elemento_encontrado_por_id(webdriver: WebDriver, id_elem_html: str): """ verifica si se encontro el elemento deseado mediante el id retorna True si se encontro el elemento en caso contrario retorna False :param webdriver: :param id_elem_html: :return: """ elemento_html = None try: webdriver.find_element_by_id(id_elem_html) return True except SelExcept.NoSuchElementException: return False
def create_post(self, driver: WebDriver, title, content, board): driver.get(self.config["hlp"]["board_url_format"].format(board=board)) form = driver.find_element_by_id("postmodify") form.find_element_by_name("subject").send_keys(title) form.find_element_by_name("message").send_keys(content) driver.save_screenshot("/tmp/pre_post.png") form.submit() driver.save_screenshot("/tmp/post_post.png")
def login(self, driver: WebDriver): driver.get("http://www.hard-light.net/forums/index.php?action=login") driver.save_screenshot("/tmp/pre_login.png") form = driver.find_element_by_id("frmLogin") form.find_element_by_name("user").send_keys(self.config["hlp"]["user"]) form.find_element_by_name("passwrd").send_keys(self.config["hlp"]["pass"]) form.submit() driver.save_screenshot("/tmp/post_login.png") time.sleep(3.)
def upload_ldss(p_browser: WebDriver, upload_file): logger = logging.getLogger('upload_ldss') p_browser.get('https://eit1-i.svcs.hp.com/cds/LoadLdssAsync') p_browser.find_element_by_css_selector('input[id = "ldssfile"]').send_keys(upload_file) validation_option = p_browser.find_element_by_css_selector('select[id = "UploadOptionList"]') validation_option.send_keys('Validate and Release') upload_button = p_browser.find_element_by_css_selector('input[value = "Upload"]') upload_button.click() time.sleep(5) for repeat in range(9): upload_status = p_browser.find_element_by_id('tbMontor').get_attribute('value') if 'go to CDS Console' in upload_status and 'Load LDSS Successful:' in upload_status: logger.info(upload_status) return True else: time.sleep(5) logger.info("DOESN'T Upload Successfully") return False
def health_check(browser : WebDriver): browser.get('https://eit1-i.svcs.hp.com/cds/HealthCheck') #Healthcompany = browser.find_element_by_css_selector('input[id = "companyCode"]') #Healthcompany.clear() #Healthcompany.send_keys("CDS50") #Submit = browser.find_element_by_css_selector('input[id = "ApplySubmitButton"]') #Submit.click() time.sleep(10) Tranrunid = browser.find_element_by_id('tranRunID').text CDSDB = cx_Oracle.connect('cds/[email protected]:1521/EONBEIT_ONBAPPL') APP_downstream = 'SM' Cursor = CDSDB.cursor() Cursor.execute('select PUB_STATE from TRAN_PUB_TARGETS where tran_run_id = :TranrunidSQL and CIS_RESP_TYPE = :ack and APPL_ID = :appid', TranrunidSQL = Tranrunid, ack = 'ACK', appid = APP_downstream ) SmokeResult = Cursor.fetchall() if all_ack_complete(SmokeResult) == True: print("Smoke testing is passed, you can start the testing") return True else: print("Smoke Testing is not passed, please hold") return False
def GetDailyWord(): capabilities = {"loggingPrefs": {}, "xwalkOptions": {"binary": "/usr/bin/xwalk", "debugPort": "12450"}} driver = WebDriver("http://127.0.0.1:9515", desired_capabilities=capabilities, keep_alive=True) driver.get("http://cn.bing.com/dict/") word = driver.find_element_by_class_name("client_daily_word_en") word_text = word.text pronounce = driver.find_elements_by_class_name("client_daily_word_pn_pn") pronounce_text = [] pronounce_text.append(pronounce[0].text) pronounce_text.append(pronounce[1].text) WriteWordList(word_text + " " + pronounce[0].text + " " + pronounce[1].text) audio = driver.find_elements_by_class_name("client_aud_o") audio1_onmouseover = audio[0].get_attribute("onmouseover") audio1_onclick = audio[0].get_attribute("onclick") DownLoad_mp3(audio[0].get_attribute("onclick").split("'")[1], word_text + "_US") audio2_onmouseover = audio[1].get_attribute("onmouseover") audio2_onclick = audio[1].get_attribute("onclick") DownLoad_mp3(audio[1].get_attribute("onclick").split("'")[1], word_text + "_UK") translate = driver.find_element_by_class_name("client_daily_word_zh") translate_text = translate.text picture1_src = driver.find_element_by_id("emb1").get_attribute("src") picture2_src = driver.find_element_by_id("emb2").get_attribute("src") picture3_src = driver.find_element_by_id("emb3").get_attribute("src") DownLoad_jpg(picture1_src, word_text + "1") DownLoad_jpg(picture2_src, word_text + "2") DownLoad_jpg(picture3_src, word_text + "3") html_src = ( '<head>\ <meta content="text/html; charset=utf-8" http-equiv="content-type" />\ <title>Daily word</title>\ <link rel="stylesheet" type="text/css" href="daily-word/daily.css"></link>\ </head>\ <body>\ <div class="client_daily_word_content">\ <div class="client_daily_words_bar">\ <div class="client_daily_word_en">\ <a id="word" href="http://bing.com.cn/dict/search?q=' + word_text + '"h="ID=Dictionary,5014.1">' + word_text + '</a>\ </div>\ <div class="client_daily_word_pn">\ <div class="client_daily_word_pn_pn" lang="en">' + pronounce_text[0] + '</div>\ <div class="client_daily_word_pn_audio">\ <div class="client_icon_container">\ <audio id="us_pronun" src=./daily-word/mp3/' + word_text + "_US.mp3" + ' controls="contrils"></audio>\ </a>\ </div>\ </div>\ </div>\ <div class="client_daily_word_pn">\ <div class="client_daily_word_pn_pn" lang="en">' + pronounce_text[1] + '</div>\ <div class="client_daily_word_pn_audio">\ <div class="client_icon_container">\ <audio id="us_pronun" src=./daily-word/mp3/' + word_text + "_UK.mp3" + ' controls="contrils"></audio>\ </a>\ </div>\ </div>\ </div>\ <div class="client_daily_word_zh">' + translate_text + '</div>\ </div>\ <div class="client_daily_pic_bar">\ <a href="http://bing.com.cn/dict/search?q=' + word_text + '"class="client_daily_pic_item" target="_blank" h="ID=Dictionary,5017.1">\ <img class="rms_img" height="80" id="emb1" src="' + "./daily-word/picture/" + word_text + "1" + ".jpg" + '" width = "80" />\ </a>\ <a href="http://bing.com.cn/dict/search?q=' + word_text + '"class="client_daily_pic_item" target="_blank" h="ID=Dictionary,5017.1">\ <img class="rms_img" height="80" id="emb2" src="' + "./daily-word/picture/" + word_text + "2" + ".jpg" + '" width = "80" />\ </a>\ <a href="http://bing.com.cn/dict/search?q=' + word_text + '"class="client_daily_pic_item" target="_blank" h="ID=Dictionary,5017.1">\ <img class="rms_img" height="80" id="emb3" src="' + "./daily-word/picture/" + word_text + "3" + ".jpg" + '" width = "80" />\ </a>\ </div>\ </div>\ </div>\ <script src="daily-word/daily.js"></script>\ </body>\ <html>\ ' ) with open(word_text + ".html", "w+") as fp: html_src = html_src.encode("utf-8") fp.write(html_src)
def download_result_ldss(p_browser: WebDriver, tran_name: str) -> str: # if not os.path.exists(dst_folder_path): # raise IOError('Invalid path ' + dst_folder_path) logger = logging.getLogger('download_ldss') with open('config.json') as f: config = json.load(f) p_browser.get(config['console_url']) input_company_code = p_browser.find_element_by_id('Filters_Company') input_company_code.clear() input_submitter = p_browser.find_element_by_id('Filters_Submitter') input_submitter.clear() input_tran_name = p_browser.find_element_by_id('Filters_TranName') input_tran_name.clear() input_tran_name = p_browser.find_element_by_id('Filters_TranName') input_tran_name.send_keys(tran_name) input_channel = p_browser.find_element_by_id('Filters_ChannelTpId') input_channel.send_keys('All Channels') checkboxes = p_browser.find_elements_by_css_selector('input[type="checkbox"]') for checkbox in checkboxes: if not checkbox.is_selected(): checkbox.click() input_tran_id = p_browser.find_element_by_id('Filters_TranId') input_tran_id.clear() input_tran_run_id = p_browser.find_element_by_id('Filters_TranRunId') input_tran_run_id.clear() input_interval = p_browser.find_element_by_id('Filters_Timefilterval') input_interval.send_keys('Last 1 Month') # btn_apply_filter = p_browser.find_element_by_id('ApplyFilterButton') # btn_apply_filter.click() tran_run_id = 0 while True: btn_apply_filter = p_browser.find_element_by_id('ApplyFilterButton') btn_apply_filter.click() time.sleep(10) rows = p_browser.find_elements_by_css_selector('tr.table_row') for row in rows: cells = row.find_elements_by_tag_name('td') for i, c in enumerate(cells): if c.text == tran_name: if cells[i + 2].text == 'Errors' or cells[i + 2].text == 'Complete': tran_run_id = cells[i + 10].text logger.info('tran_run_id: %s' % tran_run_id) input_tran_name = p_browser.find_element_by_id('Filters_TranName') input_tran_name.clear() btn_ldss = row.find_element_by_css_selector('td.context-menu-ldss') btn_ldss.click() WebDriverWait(p_browser, 300).until(EC.visibility_of_element_located((By.ID, 'pDownload'))) WebDriverWait(p_browser, 300).until(EC.invisibility_of_element_located((By.ID, 'pDownload'))) time.sleep(10) c_dir = os.getcwd() template_path = os.path.join(c_dir, 'template') file_bef = os.listdir(template_path) print(file_bef) time.sleep(10) for b in range(len(file_bef)): if tran_run_id in file_bef[b]: shutil.move(os.path.join(template_path, file_bef[b]), os.path.join(c_dir, 'ldss_output', file_bef[b])) if tran_run_id: break return tran_run_id