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 verificar_elemento_html_por_xpath(xpath: str, web_driver: WebDriver): try: web_driver.find_element_by_xpath(xpath) return True except NoSuchElementException: return False
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 confirmation_code(driver: WebDriver, email: str, password: str): time.sleep(2) logging.debug("email: " + email) logging.debug("password: "******"code": confirmation_code} else: raise Exception("Failed to fetch the confirmation code from User email.") else: raise Exception("Failed to fetch the confirmation code from User email.") confirmation_code_selectors = SELECTORS["sign up"] fill_out_input_fields(driver, confirmation_code_selectors, details) fill_input_list = find_element(driver, find_selector_by_name(SELECTORS, "submit")) fill_input_list.click() time.sleep(2) driver.find_element_by_xpath("//a[@id='signup-modal-submit-success']").click()
def delete_all_risk_details(driver: WebDriver, del_button_position: str): # 1,3,5,7,...... #/html/body/main/div[2]/section[3]/div/div[2]/div/div[2]/table/tbody/tr[5]/td/button/i # del_button_position: 5,10,15,20,25 driver.implicitly_wait(5) time.sleep(5) del_button_index = int(del_button_position) * 5 risk_detail_div_element_xpath = "//body/main/div[2]/section[3]/div/div[2]/div/div[2]/table/tbody/tr" + "[" + str( del_button_index) + "]" risk_btn_ele_xpath = risk_detail_div_element_xpath + "/td/button/i" driver.find_element_by_xpath(risk_btn_ele_xpath).click() #logging.debug("del_button_position " + str(del_button_position)) time.sleep(5) driver.implicitly_wait(5) # 12,13,14,15....... # 12 + (1 - 1), 12 + (2 - 1), 12 + (3 - 1), 12 + (4 - 1),......... #//body/div[12]/div/div/div/div[2]/div[2]/button[1]/span delete_msg_yes_index = int(12 + (int(del_button_position) - 1)) delete_message_yes_element_xpath = "//body/div" + "[" + str( delete_msg_yes_index ) + "]" + "/div/div/div/div[2]/div[2]/button[1]/span" logging.debug(delete_message_yes_element_xpath) delete_message_yes_element = driver.find_element_by_xpath( delete_message_yes_element_xpath) delete_message_yes_element.click() time.sleep(1)
def enter_business_objectives_details(driver: WebDriver, position: str, startdate: str, enddate: str, objectives: str, owner: str, plannedreviews: str): # every call of this function, click on Add Goal find_and_click(driver, element_selector_name="Add goal") time.sleep(1) # //body/main[@id='content']/div[@id='business-objectives-content']/section[4]/div[1]/div[2]/div[2]/div[1]/div[5] # /div[1]/div[1]/div[1]/textarea[1] # //body/main[@id='content']/div[@id='business-objectives-content']/section[4]/div[1]/div[2]/div[2]/div[1]/div[5] # /div[2]/button[1] objective_div_element_xpath = "//body/main[@id='content']/div[@id='business-objectives-content']/section[4]/div[1]/div[2]/div[2]/div[1]/div" + "[" + position + "]" objective_text_ele_xpath = objective_div_element_xpath + "/div[1]/div[1]/div[1]/textarea[1]" del_btn_ele_xpath = objective_div_element_xpath + "/div[2]/button[1]" start_date_ele_xpath = objective_div_element_xpath + "/div[1]/div[2]/div[1]/div/div[2]/input" end_date_ele_xpath = objective_div_element_xpath + "/div[1]/div[2]/div[2]/div/div[2]/input" owner_ele_xpath = objective_div_element_xpath + "/div[1]/div[3]/div[1]/div[2]/input[1]" planned_reviews_ele_xpath = objective_div_element_xpath + "/div[1]/div[4]/div[1]/textarea[1]" driver.find_element_by_xpath(objective_text_ele_xpath).send_keys( objectives) driver.find_element_by_xpath(start_date_ele_xpath).send_keys(startdate) driver.find_element_by_xpath(end_date_ele_xpath).send_keys(enddate) driver.find_element_by_xpath(owner_ele_xpath).send_keys(owner) driver.find_element_by_xpath(planned_reviews_ele_xpath).send_keys( plannedreviews) time.sleep(1)
def localizar_boton_perfil_usuario(driver: WebDriver, timeout: int = 7): tiempo_limite = Temporizador.obtener_tiempo_timer() + timeout while Temporizador.obtener_tiempo_timer() < tiempo_limite: # verifica si encontro folder en caso de estar en plataforma OWA 2013 if ValidacionesHTML.verificar_elemento_encontrado_por_xpath( driver, constantes_webdriver_actions. CERRAR_SESION_BTN_PERFIL_USUARIO_OWA_2013): return driver.find_element_by_xpath( constantes_webdriver_actions. CERRAR_SESION_BTN_PERFIL_USUARIO_OWA_2013) # verifica si encontro folder en caso de estar en plataforma OWA 2016 elif ValidacionesHTML.verificar_elemento_encontrado_por_xpath( driver, constantes_webdriver_actions. CERRAR_SESION_BTN_PERFIL_USUARIO_OWA_2016): return driver.find_element_by_xpath( constantes_webdriver_actions. CERRAR_SESION_BTN_PERFIL_USUARIO_OWA_2016) raise SelExcept.TimeoutException( msg= 'No fue posible localizar el boton de perfil del usuario dentro de la ' 'plataforma')
def test_order_page(browser: WebDriver, screenshoter, db, order_status): start_vertex = '1' end_vertex = '2' order_id = _create_order(TEST_USER_ID, TEST_USER_ID, start_vertex, end_vertex) _change_order_status(db.cursor(), order_id, order_status) db.commit() browser.get(f'{BASE_URL}/order/{order_id}?clientId={TEST_USER_ID}') assert browser.find_element_by_xpath( "//div[@class='order_id']/span").text == str(order_id) assert browser.find_element_by_xpath( "//div[@class='order_start_vertex']/span").text == start_vertex assert browser.find_element_by_xpath( "//div[@class='order_end_vertex']/span").text == end_vertex assert browser.find_element_by_xpath( "//div[@class='order_status']/span").text == order_status receive_button = browser.find_elements_by_id('receive-order-button') if order_status == 'READY': assert receive_button screenshoter.save() receive_button[0].click() browser.switch_to.alert.dismiss() time.sleep(1) assert browser.find_element_by_xpath( "//div[@class='order_status']/span").text == 'COMPLETED' assert not browser.find_elements_by_id('receive-order-button') else: assert not receive_button
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 run_with(self, driver: WebDriver) -> None: print("Browsing to Amazon PrimeNow website...") driver.get(URL_PRIMENOW) print("Verifying account logged in...") if not driver.find_elements_by_xpath(XPATH_PRIMENOW_HELLO_USER): with wx.MessageBox("Firefox automation profile not logged into Amazon... exiting.", "Amazon PrimeNow", wx.OK | wx.ICON_ERROR) as dlg: dlg.ShowModal() return print("Opening Amazon PrimeNow cart...") driver.find_element_by_xpath(XPATH_PRIMENOW_CART).click() driver.find_element_by_xpath(XPATH_PRIMENOW_PROCEED_TO_CHECKOUT).click() print("Waiting for delivery time to be available...") num_tries = 0 while not self.killed: if not driver.find_elements_by_xpath(XPATH_PRIMENOW_NOT_AVAILABLE): with HyperlinkDialog("Checkout time available!", title="Amazon PrimeNow", label="Open Amazon PrimeNow cart", url=URL_PRIMENOW, 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 random_select_checkbox(driver: WebDriver, element_name: str): find_and_click(driver, element_selector_name="Select") random_age_group_element_xpath = "//body/main/div[2]/section[3]/div/div/div[2]/div/div[1]/form/ul/li" \ + "["+ str(random.randint(0, 8)) + "]"+ "/label" driver.implicitly_wait(1) driver.find_element_by_xpath(random_age_group_element_xpath).click() find_and_click(driver, element_selector_name="Confirm")
def enter_trip_details(driver: WebDriver, position: str, trip_name: str): # every call of this function, click on Add Goal find_and_click(driver, element_selector_name="Add a trip") time.sleep(2) document_div_element_xpath = "/html/body/main/div[2]/section[6]/div/div[2]/div/div[2]/table/tbody/tr" + "[" + position + "]" document_text_ele_xpath = document_div_element_xpath + "/td/div/textarea" driver.find_element_by_xpath(document_text_ele_xpath).send_keys(trip_name) time.sleep(2)
def delete_all_funding_options(driver: WebDriver, position: str): actual_position = int(position) * 2 objective_div_element_xpath = "/html/body/main/div[2]/div/div/div[2]/div/div[3]/div[1]/table/tbody/tr" + "[" + str( actual_position) + "]" del_btn_ele_xpath = objective_div_element_xpath + "/td/button" driver.find_element_by_xpath(del_btn_ele_xpath).click() time.sleep(1)
def search_select_save_random_next(driver: WebDriver): counter = 0 while True: if counter >= 50: break # logging.debug("Counter: " + str(counter)) driver.implicitly_wait(1) # check for save button save_btn_found = False try: save_product_btn = driver.find_element_by_xpath( "//body/div[4]/div/div/form/div[2]/div/span/div/section[1]/div[2]/button" ) save_btn_found = True except Exception as ex: logging.debug("save button not found.Exception: " + str(ex)) if save_btn_found == True: logging.debug("Save button found") save_product_btn.click() return # look for div's and radio buttons # try: parent_1_div_element = driver.find_element_by_xpath( "//body/div[4]/div/div/form/div[2]/div/span/div/section/div") # # "/html/body/div[7]/div/div/form/div[2]/div/span/div/section/div") # ("interaction grid m-v-xs") # except Exception as e: # parent_1_div_element = driver.find_element_by_xpath("//body/div[7]/div[1]/div[1]/form[1]/div[2]/div[1]/span[1]/div[1]/section[1]/div[1]")#"interaction grid m-v-xs") child_1_div_element = parent_1_div_element.find_element_by_tag_name( "div") # ("c-fullwidth") main_div_element = child_1_div_element.find_element_by_tag_name("div") # radio button labels label_elements = main_div_element.find_elements_by_tag_name("label") radio_elements = [] for label_element in label_elements: radio_ele = None try: radio_ele = label_element.find_element_by_tag_name("input") except Exception as e: continue radio_elements.append(radio_ele) logging.debug('number of labels - ' + str(len(radio_elements))) random_label_index = random.randint(0, len(radio_elements) - 1) logging.debug('Index of radio buttons to be selected -> ' + str(random_label_index)) radio_btn_selected = radio_elements[random_label_index] radio_btn_selected.click() driver.implicitly_wait(1) search_next_btn = find_element( driver, find_selector_by_name(SELECTORS, "search next button")) search_next_btn.click() counter += 1
def delete_all_business_objectives(driver: WebDriver, del_button_position: str): # 1,3,5,7,...... # objective_div_element_xpath = "//body/main/div[2]/section[4]/div/div[2]/div[2]/div/div" + "[" + position + "]" # objective_text_ele_xpath = objective_div_element_xpath + "/div[1]/div[1]/div[1]/textarea[1]" # del_btn_ele_xpath = objective_div_element_xpath + "/div[2]/button[1]" # start_date_ele_xpath = objective_div_element_xpath + "/div[1]/div[2]/div[1]/div/div[2]/input" # end_date_ele_xpath = objective_div_element_xpath + "/div[1]/div[2]/div[2]/div/div[2]/input" # owner_ele_xpath = objective_div_element_xpath + "/div[1]/div[3]/div[1]/div[2]/input[1]" # planned_reviews_ele_xpath = objective_div_element_xpath + "/div[1]/div[4]/div[1]/textarea[1]" objective_text_area_element_index = int(del_button_position) #//body/main/div[2]/section[4]/div/div[2]/div[2]/div/div[5]/div[1]/div[1]/div/textarea objective_text_area_element_x_path = "//body/main/div[2]/section[4]/div/div[2]/div[2]/div/div" \ + "[" + str( objective_text_area_element_index) + "]" + "/div[1]/div[1]/div/textarea" objective_text_area_text_exists = True time.sleep(2) # logging.debug(objective_text_area_element_index) # logging.debug(objective_text_area_element_x_path) try: objective_text_area_text = driver.find_element_by_xpath( objective_text_area_element_x_path).text if objective_text_area_text == None or len( objective_text_area_text) <= 0: objective_text_area_text_exists = False except Exception as e: logging.error(e) objective_text_area_text_exists = False #/html/body/main/div[2]/section[4]/div/div[2]/div[2]/div/div[15]/div[2]/button/i #/html/body/main/div[2]/section[4]/div/div[2]/div[2]/div/div[5]/div[2]/button/i #/html/body/main/div[2]/section[4]/div/div[2]/div[2]/div/div[1]/div[2]/button/i # del_button_position: 5,4,3,2,1 objective_div_element_xpath = "//body/main/div[2]/section[4]/div/div[2]/div[2]/div/div" + "[" + del_button_position + "]" del_btn_ele_xpath = objective_div_element_xpath + "/div[2]/button" driver.find_element_by_xpath(del_btn_ele_xpath).click() #logging.debug("del_button_position " + str(del_button_position)) #time.sleep(2) if objective_text_area_text_exists == True: driver.implicitly_wait(1) # 12,13,14,15....... # 12 + (1 - 1), 12 + (2 - 1), 12 + (3 - 1), 12 + (4 - 1),......... #/html/body/div[16]/div/div/div/div[2]/div[2]/button[1]/i #/html/body/div[13]/div/div/div/div[2]/div[2]/button[1] delete_msg_yes_index = int(12 + (int(del_button_position) - 1)) delete_message_yes_element_xpath = "//body/div" + "[" + str( delete_msg_yes_index ) + "]" + "/div/div/div/div[2]/div[2]/button[1]" logging.debug(delete_message_yes_element_xpath) delete_message_yes_element = driver.find_element_by_xpath( delete_message_yes_element_xpath) delete_message_yes_element.click() #time.sleep(1) else: logging.debug( "objective_text_area_text_exists is False for del_button_position " + str(del_button_position))
def select_radio_button(driver: WebDriver, element_name: str): # i dont need visa driver.implicitly_wait(5) driver.find_element_by_xpath("//body/main/div[2]/section[5]/div/div[2]/div[2]/div/h2") lower_case_element_name = element_name.lower() # find_and_click(driver, element_selector_name=element_name) # logging.debug(SELECTORS["travel plan"][lower_case_element_name]) # logging.debug(SELECTORS["travel plan"][lower_case_element_name].value) radio_element_x_path = SELECTORS["travel plan"][lower_case_element_name].value radio_i_dont_need_visa_elem = driver.find_element_by_xpath(radio_element_x_path) radio_i_dont_need_visa_elem.click()
def validate_entered_country_details(driver: WebDriver, country_name: str, country_place_number: int = 1, country_max: int = 10, list_selection: int = 10): driver.implicitly_wait(1) table_element = None try: # check if the country table already exists table_element = driver.find_element_by_xpath( "/html/body/main/div[3]/span/div[2]/span/table") # if table doesnt not exists then "add a place" button must exists if table_element == None: find_and_click(driver, element_selector_name="add a place") except Exception as e: table_element = None find_and_click(driver, element_selector_name="add a place") logging.debug("table_element " + str(table_element)) if (country_place_number == 1 and table_element == None): fill_out_country_and_validate_ui(driver, country_name, list_selection=list_selection) return if country_place_number <= country_max: # if table already exists, then "add place (x) of (y)" button must exists add_place_num_btn_element = driver.find_element_by_xpath( "//body/main/div[3]/span/div[2]/button") button_text = add_place_num_btn_element.text user_entered_button_text = "Add place " + str( country_place_number) + " of " + str(country_max) if button_text != user_entered_button_text: raise Exception("Invalid Add Place button index") # if proper button index found, then click the button to add the country place name add_place_num_btn_element.click() fill_out_country_and_validate_ui(driver, country_name, list_selection=list_selection) time.sleep(2) else: logging.debug( "Country " + str(country_name) + " cannot be added as the CountryPlaceNumber exceeding max limit.") list_country = "//body/main/div[4]/div/section/div[2]/div/ul/li" + "[" + country_place_number + "]" list_selection = list_country + "/button" driver.find_element_by_xpath(list_selection).click() time.sleep(2)
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 enter_document_details(driver: WebDriver, position: str, document_name: str, notes: str): # every call of this function, click on Add Goal find_and_click(driver, element_selector_name="Add another document") time.sleep(2) document_div_element_xpath = "/html/body/main/div[2]/section[6]/div/div/div/form/div/div/div[5]/div" + "[" + position + "]" document_text_ele_xpath = document_div_element_xpath + "/div[1]/div[2]/input" notes_ele_xpath = document_div_element_xpath + "/div[2]/textarea" driver.find_element_by_xpath(document_text_ele_xpath).send_keys( document_name) driver.find_element_by_xpath(notes_ele_xpath).send_keys(notes) time.sleep(2)
def enter_risk_details(driver: WebDriver, position: str, risktext: str, contingencyplan: str): # every call of this function, click on Add Goal find_and_click(driver, element_selector_name="Add a risk") time.sleep(1) position = int(position) risktext_position = int((int(position) * 5) - 4) risk_div_element_xpath = "//body/main/div[2]/section[3]/div/div[2]/div/div[2]/table/tbody/tr" + "[" + str( risktext_position) + "]" risk_text_ele_xpath = risk_div_element_xpath + "/td/div[2]/textarea" driver.find_element_by_xpath(risk_text_ele_xpath).send_keys(risktext) logging.debug(risk_text_ele_xpath) logging.debug(risktext) time.sleep(1) path_random_risk_likelihood = "//body/main/div[2]/section[3]/div/div[2]/div/div[2]/table/tbody/tr" \ + "[" + str(risktext_position + 1) + "]" + "/td/div[2]/div" \ + "[" + str(random.randint(1, 5)) + "]" path_random_risk_likelihood_button_ele_xpath = path_random_risk_likelihood + "/label" driver.find_element_by_xpath( path_random_risk_likelihood_button_ele_xpath).click() time.sleep(1) risk_impact_button_element_xpath = "//body/main/div[2]/section[3]/div/div[2]/div/div[2]/table/tbody/tr" \ + "[" + str(risktext_position + 2) + "]" \ + "/td/div[2]/div"+ "[" + str(random.randint(1, 5)) + "]" + "/label" driver.find_element_by_xpath(risk_impact_button_element_xpath).click() contingencyplan_div_element_xpath = "//body/main/div[2]/section[3]/div/div[2]/div/div[2]/table/tbody/tr" \ + "[" + str(risktext_position + 3) + "]" contingencyplan_text_element_xpath = contingencyplan_div_element_xpath + "//td/div[2]/textarea" driver.find_element_by_xpath(contingencyplan_text_element_xpath).send_keys( contingencyplan) time.sleep(5)
def search(self, webdriver: WebDriver, search: str): input = webdriver.find_element_by_xpath("//input[@id='id-search-field']") input.clear() input.send_keys(search) input.send_keys(Keys.RETURN) WebDriverWait(webdriver, 15).until( EC.visibility_of_element_located((By.XPATH, "//h3[contains(text(),'Results')]")))
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(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 slot(save_dir: str, driver: WebDriver): """ スロット """ url = 'https://aw.mobadme.jp/slot/play?m_id=1528' success = True driver.get(url) # スロットは処理に時間がかかるので長めに設定 slot_wait = WebDriverWait(driver, 20) try: current = driver.current_url # 開始ボタン(ここは長めに待つ) start = driver.find_element_by_xpath( '//*[@id=\"enchant-stage\"]/div/div[57]') start.click() # URLが結果画面になるのを待つ slot_wait.until(lambda driver: driver.current_url != current) driver.save_screenshot( '%s/slot_%s.png' % (save_dir, datetime.datetime.now().strftime('%Y%m%d%H%M%S'))) except: utils.LOGGER.warn(" スロットはプレイ済みでした。") # ステータス更新 RESULTS.slot = { 'success': success }
def data_mining(driver: WebDriver): """ Main function providing flow to the app. Next page button is different on first page then on others so when page is not having the next page button the button's value is changed to boolean which means last article page. Program goes through last page's articles and breaks loop. :param driver: WebDriver :return: """ driver.get("https://teonite.com/blog/") driver.maximize_window() next_page_button = driver.find_element_by_css_selector( "ul.pagination-list>li.blog-button.post-pagination>a") while True: main_window = driver.window_handles[0] articles = driver.find_elements_by_class_name("post-container") for article in articles: article_title = get_article_title(article) open_article_in_new_tab(driver, article, article_title) save_article_in_db(driver, article_title) driver.close() driver.switch_to.window(main_window) if not isinstance(next_page_button, bool): next_page_button.click() try: next_page_button = driver.find_element_by_xpath( "//*[@id='blog-posts']/div/ul/li[2]/a") except NoSuchElementException: next_page_button = False else: driver.close() break
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 find_task_by_name(browser: WebDriver, task_name) -> Optional[WebElement]: """ find tag label with the task text in it :return: outer li tag """ found_li = browser.find_element_by_xpath( f'//label[text()="{task_name}"]/../..') return found_li
def delete_all_document_details(driver: WebDriver, del_button_position: str): # 1,3,5,7,...... # del_button_position: 5,4,3,2,1 document_div_element_xpath = "//body/main/div[2]/section[6]/div/div[2]/div/form/div/div/div[5]/div" + "[" + del_button_position + "]" del_btn_ele_xpath = document_div_element_xpath + "/div[3]/button" driver.find_element_by_xpath(del_btn_ele_xpath).click() logging.debug("del_button_position " + str(del_button_position)) driver.implicitly_wait(1) delete_msg_yes_index = int(12 + (int(del_button_position) - 1)) delete_message_yes_element_xpath = "//body/div" + "[" + str( delete_msg_yes_index) + "]" + "/div/div/div/div[2]/div[2]/button[1]" logging.debug(delete_message_yes_element_xpath) delete_message_yes_element = driver.find_element_by_xpath( delete_message_yes_element_xpath) delete_message_yes_element.click()
def delete_all_funding_options(driver: WebDriver, del_button_position: str): # 1,3,5,7,...... time.sleep(1) funding_options_div_element_xpath = "//body/main/div[2]/div/div/div[2]/div/div[3]/div[1]/table/tbody/tr" + "[" + del_button_position + "]" del_btn_ele_xpath = funding_options_div_element_xpath + "/td/button" driver.find_element_by_xpath(del_btn_ele_xpath).click() driver.implicitly_wait(2) delete_msg_yes_index = int(12 + (int((int(del_button_position) / 2)) - 1)) time.sleep(1) delete_message_yes_element_xpath = "//body/div" + "[" + str( delete_msg_yes_index) + "]" + "/div/div/div/div[2]/div[2]/button[1]" logging.debug(delete_message_yes_element_xpath) delete_message_yes_element = driver.find_element_by_xpath( delete_message_yes_element_xpath) delete_message_yes_element.click()
def verificar_elemento_encontrado_por_xpath(webdriver: WebDriver, xpath: str): """ verifica si se encontro el elemento deseado mediante el xpath retorna True si se encontro el elemento en caso contrario retorna False :param webdriver: :param xpath: :return: """ elemento_html = None try: webdriver.find_element_by_xpath(xpath) return True except SelExcept.NoSuchElementException as e: return False
def fill_out_product(driver: WebDriver, products: str): product_btn = find_element( driver, find_selector_by_name(SELECTORS, "product-btn") ) product_btn.click() if driver.find_element_by_css_selector("body > div:nth-child(11) > div > div > button").is_displayed(): driver.find_element_by_css_selector("body > div:nth-child(11) > div > div > button").click() driver.find_element_by_xpath( "//body/div[2]/nav/span[2]/span/button") #"//body/div[3]/div[1]/div[1]/form[1]/div[2]/div[1]/div[1]/div[2]/div[1]/input[1]").send_keys(products) driver.find_element_by_xpath( "//body/div[3]/div[1]/div[1]/form[1]/div[2]/div[1]/div[1]/div[2]/button[1]/i[1]").click() while True: find_and_select_random_radio_and_click_next(driver) time.sleep(1) # seconds try: if driver.find_element_by_xpath("//button[contains(text(),'Save product')]").is_displayed(): driver.find_element_by_xpath("//button[contains(text(),'Save product')]").click() break else: continue except: pass
def parse_from_vk_dev(url: str, web_driver: WebDriver): open_url(url, web_driver) waiter = wait.WebDriverWait(web_driver, 10) button_xpath = '//*[@id="dev_req_run_btn"]' waiter.until(expected_conditions.visibility_of_element_located( locator=(By.XPATH, button_xpath))) button = web_driver.find_element_by_xpath(button_xpath) button.click() waiter.until(expected_conditions.text_to_be_present_in_element( locator=(By.XPATH, button_xpath), text_='Run')) res = web_driver.find_element_by_xpath('//*[@id="dev_result"]') links = [element.get_attribute('href') for element in res.find_elements_by_tag_name('a')] json = load_vk_json(res.text) for item in json['response']['items']: for attachment in item.get('attachments', []): type_ = attachment['type'] if type_ in {'photo', 'sticker'}: set_links_to_photo(attachment[type_], links) elif type_ in {'audio', 'doc'}: set_plain_link(attachment[type_], links) elif type_ == 'video': set_links_to_video(attachment[type_], links) return json
class Browser: name = None capname = None supports_alert = True def __init__(self): self.driver = None self.profiledir = None self.initialized = False def initialSetup(self): pass def start(self): if self.driver: raise RuntimeError('%s is already running' % self.name) caps = {} caps.update(getattr(DesiredCapabilities, self.capname)) self.prepare_caps(caps) self.driver = WebDriver( 'http://%s:%d/wd/hub' % (self.args.server_host, self.args.server_port), desired_capabilities = caps ) self.driver.implicitly_wait(2) time.sleep(3) for h in self.driver.window_handles[1:]: self.driver.switch_to.window(h) self.driver.close() self.driver.switch_to.window(self.driver.window_handles[0]) self.driver.switch_to_default_content() if not self.initialized: self.initialSetup() self.initialized = True def quit(self): try: if self.driver: self.driver.quit() self.driver = None except http_client.BadStatusLine: pass def create_profile(self): self.profiledir = os.path.join(self.testdir, 'profile', self.name) if os.path.exists(self.profiledir): shutil.rmtree(self.profiledir) os.makedirs(self.profiledir) return self.profiledir def set_window_size(self, width, height): self.driver.set_window_size(width, height) @property def url(self): return self.driver.current_url def wait_page_load(self): time.sleep(1) self.wait_until(lambda d: self.js('return !!(window.document&&window.document.readyState==="complete")')) def open(self, url): self.driver.get(url) self.wait_page_load() def reload(self): self.open(self.url) def wait_until(self, callback): wait = WebDriverWait(self.driver, 20) return wait.until(callback) def ac(self): return ActionChains(self.driver) def q(self, selector, context = None): if context is None: return self.driver.find_element_by_css_selector(selector) return context.find_element_by_css_selector(selector) def qa(self, selector, context = None): if context is None: return self.driver.find_elements_by_css_selector(selector) return context.find_elements_by_css_selector(selector) def x(self, xpath): return self.driver.find_element_by_xpath(xpath) def xa(self, xpath): return self.driver.find_elements_by_xpath(xpath) def alert_accept(self): if self.supports_alert: Alert(self.driver).accept() else: raise RuntimeError('%s not supports alert handling' % self.name) def js(self, script, *args): return self.driver.execute_script(script, *args) def geom(self, element): return self.geom2(element)[:4] def geom2(self, element): return tuple(map(round, self.js(''' var elem = arguments[0]; var rect = elem.getBoundingClientRect(); return [rect.left, rect.top, rect.width, rect.height, rect.left + rect.width, rect.top + rect.height]; ''', element))) def screen_size(self): sw, sh = self.js(''' return [document.documentElement.clientWidth, document.documentElement.clientHeight]; ''') return sw, sh def set_cookie(self, name, value, domain, path): expires = '' if value is None: value = '' expires = '; expires=Thu, 01 Jan 1970 00:00:00 GMT' cookie = '%s=%s; domain=%s; path=%s%s' % (name, value, domain, path, expires) self.js('document.cookie=%s' % json.dumps(cookie)) def screenshot(self, elem = None): ss = self.driver.get_screenshot_as_png() io = util.BytesIO(ss) img = Image.open(io) if elem is not None: x, y, w, h = tuple(map(int, self.geom(elem))) img = img.crop((x, y, x + w, y + h)) return img.convert('RGB') def download(self, url, filename): dlpath = os.path.join(self.browserdir, filename) if not os.path.exists(dlpath) or os.stat(dlpath).st_mtime < time.time() - 60 * 60 * 24: util.download(url, dlpath) return dlpath def read_file_as_base64(self, filename): fp = open(filename, 'rb') try: data = fp.read() finally: fp.close() data = base64.b64encode(data) try: data = str(data, 'ascii') except TypeError: pass return data