def deselect_g(context, selector, text=None, *argv, index=None, value=None, **kw): germanium = find_germanium_object(context) select_element = _element(germanium, selector) s = Select(select_element) if text is not None: for single_text in _ensure_list(text): s.deselect_by_visible_text(single_text) if index is not None: for single_index in _ensure_list(index): single_index = int(single_index) s.deselect_by_index(single_index) if value is not None: for single_value in _ensure_list(value): s.deselect_by_value(single_value) if not text and not index and not value: s.deselect_all()
def selector(self, index=None, value=None, text=None, de_index=None, de_value=None, de_text=None, de_all=False): s = Select(self.element) if index: s.select_by_index(index) elif value: s.select_by_value(value) elif text: s.select_by_visible_text(text) elif de_index: s.deselect_by_index(de_index) elif de_value: s.deselect_by_value(de_value) elif de_text: s.deselect_by_visible_text(de_text) elif de_all: s.deselect_all() else: return None
def deselect(self, value) -> 'Pylenium': """ Deselects an `<option>` within a multi `<select>` element. Args: value: The value or text content of the `<option>` to be deselected. Raises: `ValueError` if this element is not a `<select>` Returns: The current instance of Pylenium so you can chain another command. """ self.py.log.info(' [STEP] .deselect() - Deselect this element') if self.webelement.tag_name != 'select': raise ValueError( f'Can only perform Deselect on <select> elements. Tag name: {self.webelement.tag_name}' ) select = Select(self.webelement) if not select.is_multiple: raise NotImplementedError( f'Deselect can only be performed on multi-select elements.') try: select.deselect_by_visible_text(value) except NoSuchElementException: select.deselect_by_value(value) finally: return self.py
def remove_selection(self, locator, optionLocator): el = self.driver.find_element(self.getBy(selectLocator), self.getValue(selectLocator)) select = Select(el) logging.debug(select.options) if "label=" in optionLocator: select.deselect_by_visible_text(optionLocator[6:]) elif "value=" in optionLocator: select.deselect_by_value(optionLocator[6:])
def deselect_option_by_text(locatorMethod, locatorExpression, option_text, *args): u"""取消勾选选中项根据文本""" global driver try: select = Select(getElement(driver, locatorMethod, locatorExpression)) select.deselect_by_visible_text(option_text) except Exception, e: raise e
def remove_selection(self, locator, optionLocator): el = self.driver.find_element(self.getBy(selectLocator), self.getValue(selectLocator)) select = Select(el) logging.debug(select.options) if ("label=" in optionLocator): select.deselect_by_visible_text(optionLocator[6:]) elif ("value=" in optionLocator): select.deselect_by_value(optionLocator[6:])
def deselectoptionfromdrpdwn(self,option,locatorvalue,locatortype="id/name/xpath/css/linktext/partiallinktext"): try: element = self.getElement(locatorvalue,locatortype) s1 = Select(element) s1.deselect_by_visible_text(option) self.log.info("Deselected option - "+option+"from element with locator type "+locatortype +" and locator value "+locatorvalue) except Exception as e: self.log.error("Unable to deselect option from element with locator type "+locatortype+" and locator value "+ locatorvalue +str(e)) return False
def deselect(self, input, type='index'): #下拉选 selector = Select(self.element) if type == "index": selector.deselect_by_index(input) elif type == "value": selector.deselect_by_value(input) elif type == "text": selector.deselect_by_visible_text(input) else: selector.deselect_all()
def deselect_option(self, value=None, text=None, index=None): if len(list(filter(None, (value, text, index)))) != 1: raise ValueError("You must supply exactly one of (value, text, index) kwargs") select = Select(self) if value is not None: select.deselect_by_value(value) elif text is not None: select.deselect_by_visible_text(text) else: select.deselect_by_index(index)
def deselect_option(self, value=None, text=None, index=None): if len(list(filter(None, (value, text, index)))) != 1: raise ValueError("You must supply exactly one of (value, text, index) kwargs") select = Select(self) if value is not None: select.deselect_by_value(value) elif text is not None: select.deselect_by_visible_text(text) else: select.deselect_by_index(index)
def deselectText(self, idpro, value, selectValue): el = self.webObject.testEle(idpro=idpro, value=value) try: s = Select(el) s.deselect_by_visible_text(selectValue) log.info("取消按文本选择,根据对象{0}[{1}],取消选择成功".format(idpro, value)) except AssertionError as e: screenshotdir = saveScreenShot(self.driver) log.error("取消按文本选择,根据对象{0}[{1}],取消选择失败,错误截图请见:{2}".format( idpro, value, screenshotdir)) raise e
def deselectoptionfromdrpdwn(self, locatorvalue, visbletext="India", locatortype="id"): try: element = self.getElement(locatorvalue, locatortype) sel = Select(element) sel.deselect_by_visible_text(visbletext) self.log.info("DeSelected option " + visbletext + " in drp dwn") except Exception as e: self.log.error("Unble to DeSelect option " + visbletext + " in drp dwn" + e)
def __delitem__(self, key): s = WebDriverSelect(self.driver.find_element_by_locator(self.locator)) method = key[:key.find("=")] value = key[key.find("=") + 1:] if method == "value": s.deselect_by_value(value) elif method == "index": s.deselect_by_index(value) elif method == "text": s.deselect_by_visible_text(value) else: raise saunter.exceptions.InvalidLocatorString("%s is an invalid locator" % item)
def deSelect(self): fruit = op.driver.find_element_by_css_selector( "#multiple-select-example") de = Select(fruit) time.sleep(2) de.deselect_by_visible_text("Orange") time.sleep(2) de.select_by_visible_text("Orange") time.sleep(2) de.deselect_all() time.sleep(2)
def __delitem__(self, key): s = Select(self.driver.find_element(*self.locator)) method = key[:key.find("=")] value = key[key.find("=") + 1:] if method == "value": s.deselect_by_value(value) elif method == "index": s.deselect_by_index(value) elif method == "text": s.deselect_by_visible_text(value) else: raise Exception("%s is an invalid locator" % item)
def __delitem__(self, key): s = WebDriverSelect(self.driver.find_element_by_locator(self.locator)) method = key[:key.find("=")] value = key[key.find("=") + 1:] if method == "value": s.deselect_by_value(value) elif method == "index": s.deselect_by_index(value) elif method == "text": s.deselect_by_visible_text(value) else: raise saunter.exceptions.InvalidLocatorString( "%s is an invalid locator" % item)
def Base_select(self, param): """ - name: select 1st select: id: element1 by_index: 1 - name: select by value select: id: element1 by_value: value1 - name: select by visible text select: id: element1 by_text: "text 1" """ elem = self.findone(param) if elem is None: raise Exception("element not found: %s" % (param)) flag = param.get("deselect", False) sel = Select(elem) if "by_index" in param: if flag: sel.deselect_by_index(param.get("by_index")) else: sel.select_by_index(param.get("by_index")) elif "by_value" in param: if flag: sel.deselect_by_value(param.get("by_value")) else: sel.select_by_value(param.get("by_value")) elif "by_text" in param: if flag: sel.deselect_by_visible_text(param.get("by_text")) else: sel.select_by_visible_text(param.get("by_text")) elif param.get("all", False): if flag: sel.deselect_all() else: sel.select_all() retp = param.get("return", "selected") if retp == "selected": res = sel.all_selected_options elif retp == "first": res = sel.first_selected_option elif retp == "all": res = sel.options else: return return self.return_element(param, res)
def verify_static_dropdown(): # ARRANGE driver = webdriver.Chrome( "/Users/gaurnitai/Desktop/PySeBootcamp/drivers/chromedriver") driver.get("https://www.facebook.com/") driver.maximize_window() time.sleep(4) day_loc = driver.find_element_by_id("day") select_day = Select(day_loc) select_day.select_by_value("4") # 4 time.sleep(3) month_loc = driver.find_element_by_xpath("//select[@title='Month']") select_day = Select(month_loc) select_day.select_by_visible_text("Mar") # Mar time.sleep(3) year_loc = driver.find_element_by_name("birthday_year") select_day = Select(year_loc) select_day.select_by_index(3) # 2018 time.sleep(3) # This is for deselect functions select_day = Select(day_loc) select_day.deselect_by_value("4") # 4 time.sleep(3) month_loc = driver.find_element_by_xpath("//select[@title='Month']") select_day = Select(month_loc) select_day.deselect_by_visible_text("Mar") # Mar time.sleep(3) year_loc = driver.find_element_by_name("birthday_year") select_day = Select(year_loc) select_day.deselect_by_index(3) # 2018 driver.close() driver.quit()
def select(self, locator, option, optionType='text', locatortype='xpath'): try: select = Select( self.element(locator=locator, locatortype=locatortype)) optiontype = str(optionType).lower() if optiontype == 'index': select.deselect_by_index(option) elif optiontype == 'text': select.deselect_by_visible_text(option) elif optiontype == 'value': select.deselect_by_value(option) else: self.logs.info("please give some option type in option or" + "option" + "is not able to select") except: self.logs.error("not able to select locator -> " + locator)
def deselect_by_given(self, locator: str, way: int, value=None): """ 使用给定方式,取消已选下拉框选项(适用于原生select下拉框元素) :param locator: :param way: 1 通过index选取,2 通过value属性值选取,3 通过文本值选取,4 取消全部 :param value: 给定index或value属性值或文本值 :return: """ element_obj = self.find_element(locator) select = Select(element_obj) if way == 1: select.deselect_by_index(value) elif way == 2: select.deselect_by_value(value) elif way == 3: select.deselect_by_visible_text(value) elif way == 4: if select.is_multiple: select.deselect_all() self._log.info('已取消已选下拉框选项')
def select_value(self, locator, value): """ 下拉框选项 :param locator: :param value: value=value/text=text,index=1 :return: """ if isinstance(locator, tuple): el = self.get_element(locator) else: el = locator select = Select(el) _s = value.split('=')[0].strip().lower() _v = value.split('=')[1].strip().lower() if _s == 'value': select.deselect_by_value(_v) elif _s == 'text': select.deselect_by_visible_text(_v) elif _s == 'index': select.deselect_by_index(_v)
def browser_launch(self): self.driver.get("file:///C:/Users/shekar/PycharmProjects/Selenium_July/htmlpages/page6.html") self.driver.maximize_window() #Single select drop down ele1 = self.driver.find_element(By.XPATH, "(//select[@name='Countries'])[1]") sel = Select(ele1) sel.select_by_index(1) time.sleep(2) sel.select_by_visible_text("China") time.sleep(2) sel.select_by_value("NZ") #Multi select drop down ele1 = self.driver.find_element(By.XPATH, "(//select[@name='Countries'])[2]") sel = Select(ele1) sel.select_by_index(1) time.sleep(2) sel.select_by_visible_text("China") time.sleep(2) sel.select_by_value("NZ") #deselcting the options in multi select drp dwn time.sleep(2) sel.deselect_by_index(1) time.sleep(2) sel.deselect_by_visible_text("China") time.sleep(2) sel.deselect_by_value("NZ") #Deselecting all options selected in multi select drp dwn sel.deselect_all() time.sleep(10) self.driver.close()
def test(self): #for firefox at first we have to show the path where is the Geckodriver located #we set a variable "driverlocation" which will store the driver path driverlocation = "/usr/local/bin/gecko_driver/geckodriver" #now instantiate the firefox browser with the parameter of driver location driver = webdriver.Firefox(executable_path=driverlocation) # At first maximize the window driver.maximize_window() # Open The Provided URL with driver.get method baseURL = "http://www.letskodeit.teachable.com/p/practice" driver.get(baseURL) # wait until the browser is fully loaded by implicitly_wait method driver.implicitly_wait(10) # Find the drop down element dropdownelement =driver.find_element_by_id("carselect") #now select the element by Selenium provided method Select() select_element = Select(dropdownelement) #now work with the selected element select_element.select_by_value("benz") print ("Select Benz by value") time.sleep(2) select_element.deselect_by_visible_text("BMW") print ("Select BMW by visible text") time.sleep(2) select_element.deselect_by_index("2") print ("Select Honda by index") time.sleep(2) print ("Select Benz by value") time.sleep(2)
def test_select(self): """ Test select and malty select """ # Open FireFox and Load page self.driver.get(self.base_url + '/example2/') self.assertTitle('example 2') in3 = Select(self.find(name='in3')) in4 = Select(self.find(name='in4')) # check that progress return back in3.select_by_visible_text('2') self.assertProgress('progress2', 40) in3.select_by_visible_text('something') self.assertProgress('progress2', 0) # send data and check that it is saved in3.select_by_visible_text('3') in4.select_by_visible_text('1') self.assertProgress('progress2', 60) in4.select_by_visible_text('2') self.assertProgress('progress2', 80) # check that progress return back in4.deselect_by_visible_text('2') self.assertProgress('progress2', 60) in4.select_by_visible_text('2') in4.select_by_visible_text('3') self.assertProgress('progress2', 100) in4.select_by_visible_text('4') self.assertProgress('progress2', 100) self.assertButtonDisabled()
def _select_combo_box(self, combo_box_identifier, option_name=None, page_load=False, timeout=5, option_name_list=None, by=By.NAME): """ DESCRIPTION: Find the select element defined by combo_box_identifier and by, and select the provided option(s). If page_load is True, wait during timeout seconds until a new page is loaded before returning. In case of a multiple selection, clear the previous selection before doing any new selection. If the combo box is a single combo box, and option name is already selected, it will return immediately, even if page_load is set to True. The same happens if the combo box is a multiple combo box, and option_name_list matches exactly the current selected options. INPUT: combo_box_identifier: The identifier used to find the combo box. This parameter and the "by" parameter are used together to create a locator. option_name: The name of a single option to select. Exactly one among option_name and option_name_list must be provided. If option_name is provided and the combo box is a multiple combo box, it is strictly identical as if option_name_list was provided as an iterable of 1 element. The selection is done according to the displayed text of the option, and not according to its value. The default value is None. page_load: If it is True, the function will wait for a new page being loaded before returning. If the combo box is a multiple combo box, and option_name_list contains more than 1 element, it will wait between each selection. The default value is False. timeout: The number of seconds to wait before raising a TimeoutException if a new page does not load. option_name_list: An iterator containing the name of options to select. Exactly one among option_name and option_name_list must be provided. If option_name_list is provided, but the combo box is a single combo box, a RuntimeError is raised, even if option_name_list contains only 1 element. The selection is done according to the displayed text of the option, and not according to its value. The default value is None. by: Defined how the combo box will be looked for. It forms a locator with combo_box_identifier. The default value is By.Name. OUTPUT: Return True if at least one selection has been performed, otherwise False. In other words, return False if the selected option matches with the provided option_name for a single combo box, or if the selected options match with the provided option_name_list for a multiple combo box. ERROR: Raise a RuntimeError if neither or both of option_name and option_name_list are not None. Raise a RuntimeError if option_name_list is provided, but the combo box is a single combo box. Raise a TimeoutException if page_load is True but the page did not refresh in timeout seconds. Raise a StaleElementReferenceException if the combo box is a multiple combo box, more than one selection need to be done and page_load is False whereas the page is refreshed between each selection. Raise a UnexpectedTagNameException when the locator (combo_box_identifier, by) locates an element, but this element is not a combo box. Raise a NoSuchElementException when no element can be referred by the locator (combo_box_idenfifier, by). """ if (option_name is None and option_name_list is None) or (option_name is not None and option_name_list is not None): raise RuntimeError("Exactly 1 among option_name and option_name_list must be None") select_element = self.driver.find_element(by, combo_box_identifier) is_multiple = select_element.get_attribute("multiple") select_element = Select(select_element) if option_name_list is not None and not is_multiple: raise RuntimeError("Can't select multiple value in a single select") if option_name is not None: # If the value is already selected, there is nothing to be done if select_element.first_selected_option.text == option_name: return False option_name_list = [option_name] if is_multiple: if set([option.text for option in select_element.all_selected_options]) == set(option_name_list): return False if page_load: # We have to deselect element one by one, as the select element will stale with deselect_all while len(select_element.all_selected_options) != 0: option = select_element.first_selected_option with self.wait_for_page_load(timeout): select_element.deselect_by_visible_text(option.text) # As the page is reloaded, we have to look again for the element select_element = Select(self.driver.find_element(by, combo_box_identifier)) else: select_element.deselect_all() for option_name in option_name_list: if page_load: with self.wait_for_page_load(timeout): select_element.select_by_visible_text(option_name) # As the page is reloaded, we have to look again for the element in case of multiple selection select_element = Select(self.driver.find_element(by, combo_box_identifier)) else: select_element.select_by_visible_text(option_name) return True
#select the options from multi-select dropdown from selenium import webdriver from time import sleep from selenium.webdriver.support.select import Select driver = webdriver.Chrome() driver.get("file:///C:/Users/Ashwini/Desktop/HTML_Files/multipleDropDown.html") driver.maximize_window() dropdown = driver.find_element_by_name("D1") select = Select(dropdown) sleep(2) select.select_by_visible_text("Dosa") sleep(2) select.select_by_value("Puri") sleep(2) select.select_by_index(4) sleep(2) select.deselect_by_index(2) sleep(2) select.deselect_by_value("Upma") sleep(2) select.deselect_by_visible_text("Puri") driver.close()
def CreationCH(dataCH, tasks, countRB): try: #Datos username = dataCH[0][1] password = dataCH[1][1] user = username + '@directvla.com.co' nameCH = dataCH[2][1] #Driver driver = webdriver.Chrome("./resources/chromedriver.exe") driver.set_window_size(1152, 840) #Abre página Jira driver.get("https://directvla.jira.com/projects/CH/board") #Confirma que si es la página Login assert "Log in to continue - Log in with Atlassian account" in driver.title driver.implicitly_wait(20) #Página Loggging Jira driver.find_element_by_id("username").send_keys(user) driver.find_element_by_xpath("//*[@id='login-submit']/span/span/span").click() #Página Loggging Jira-Username/Password eleUsername = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.ID, "userid")) ) eleUsername.send_keys(username) driver.find_element(By.ID, "password").send_keys(password) driver.find_element(By.ID, "submit-btn").click() time.sleep(10) #Click Crear cambio eleCreate = WebDriverWait(driver, 15).until( EC.presence_of_element_located(( By.CSS_SELECTOR, "#createGlobalItem .css-t5emrf")) ) eleCreate.click() time.sleep(5) #Ingreso datos CH y su creación driver.find_element(By.CSS_SELECTOR, "#issuetype-single-select > .icon").click() #Issue Type driver.find_element(By.ID, "issuetype-field").send_keys("Normal Change Request") driver.find_element(By.ID, "issuetype-field").send_keys(Keys.ENTER) time.sleep(2) driver.find_element(By.ID, "summary").send_keys(nameCH) driver.find_element(By.ID, "customfield_25269-2").click() driver.find_element(By.ID, "create-issue-submit").click() #Seleciona y redirecciona al CH creado eleSel = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, ".issue-created-key")) ) eleSel.click() #Establecer old view driver.implicitly_wait(20) urlch = driver.current_url urlch = urlch + '?oldIssueView=true' driver.get(urlch) #Seleciona crear sub.task eleSub = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, "#opsbar-operations_more > .icon")) ) eleSub.click() driver.find_element(By.ID, "create-subtask").click() time.sleep(10) #Creación de subtareas countT = 0 countP = 1 numT = len(tasks) - 1 for task,group,typeT,hourS,hourF,descriptionT in tasks: summaryD = task + " - " + group descriptionR = "Ejecutar las tareas descritas en el documento adjunto." time.sleep(8) driver.find_element(By.CSS_SELECTOR, "#issuetype-single-select > .icon").click() #Issue Type driver.find_element(By.ID, "issuetype-field").send_keys(task) driver.find_element(By.ID, "issuetype-field").send_keys(Keys.ENTER) if task == 'Schedule Assessment' or task == 'Technical Assessment' or task == 'Authorization': time.sleep(2) driver.find_element(By.CSS_SELECTOR, "#summary").send_keys(summaryD) #Summary driver.find_element(By.ID, "description").send_keys(summaryD) time.sleep(1) if task == 'Technical Assessment' : selAss = Select(driver.find_element_by_id('customfield_24683')) #Assessment Type selAss.select_by_visible_text(typeT) if task == 'Schedule Assessment' or task == 'Technical Assessment' : selGroup = Select(driver.find_element_by_id('customfield_25033')) # Owner group selector selGroup.select_by_visible_text(group) if task == 'Authorization' : selGroup = Select(driver.find_element_by_id('customfield_25122')) #Owner gruop selector selGroup.select_by_visible_text(group) if task == 'Implementation Activity' or task == 'Validation Activity' or task == 'RollBack Activity': if task == 'Implementation Activity': nameRO = str(countP) + ". RollOut - " + typeT + " - " + group if task == 'Validation Activity': nameRO = str(countP) + ". " + task + " - " + group descriptionR = "Validar las tareas desplegadas." if task == 'RollBack Activity': nameRO = str(countP) + ". " + task + " - " + typeT + " - " + group countRB -= 1 if descriptionT != None : descriptionR = descriptionT time.sleep(5) driver.find_element(By.CSS_SELECTOR, "#summary").send_keys(nameRO) #Summery driver.find_element(By.ID, "description").send_keys(descriptionR) #Description hourS = hourS.strftime("%d/%b/%y %I:%M %p") driver.find_element(By.ID, "customfield_24668").clear() #Start Date driver.find_element(By.ID, "customfield_24668").click() driver.find_element(By.ID, "customfield_24668").send_keys(hourS) hourF = hourF.strftime("%d/%b/%y %I:%M %p") driver.find_element(By.ID, "customfield_24667").clear() #Finish Date driver.find_element(By.ID, "customfield_24667").click() driver.find_element(By.ID, "customfield_24667").send_keys(hourF) selGroup = Select(driver.find_element_by_id('customfield_25033')) #Owner gruop selector selGroup.select_by_visible_text(group) countP += 1 if countT == 0: driver.find_element(By.CSS_SELECTOR, ".qf-create-another").click() #Create another sub-task if countRB == 0 and countT == numT: driver.find_element(By.CSS_SELECTOR, ".qf-create-another").click() #No Create another sub-task countT += 1 driver.find_element(By.ID, "create-issue-submit").click() #Create a subtask buttom time.sleep(16) #Modifica la opción Edit driver.find_element(By.ID, "action_id_231").click() time.sleep(10) driver.find_element(By.ID, "description").click() #Description driver.find_element(By.ID, "description").send_keys(dataCH[3][1]) selGroup = Select(driver.find_element_by_id('customfield_25033')) # Owner group selector selGroup.select_by_visible_text(dataCH[4][1]) sDate = dataCH[5][1].strftime("%d/%b/%y %I:%M %p") driver.find_element(By.ID, "customfield_24668").click() # Start date and time driver.find_element(By.ID, "customfield_24668").send_keys(sDate) fDate = dataCH[6][1].strftime("%d/%b/%y %I:%M %p") driver.find_element(By.ID, "customfield_24667").click() # End date and time driver.find_element(By.ID, "customfield_24667").send_keys(fDate) ofDate = dataCH[7][1].strftime("%d/%b/%y %I:%M %p") driver.find_element(By.ID, "customfield_24775").click() #Outage date from driver.find_element(By.ID, "customfield_24775").send_keys(ofDate) otDate = dataCH[8][1].strftime("%d/%b/%y %I:%M %p") driver.find_element(By.ID, "customfield_24776").click() #Outage date to driver.find_element(By.ID, "customfield_24776").send_keys(otDate) typeI = "Country" #Country css = EditCountryArea(typeI,dataCH[9][1]) driver.find_element(By.ID, css).click() typeI = "Area" #Impacted Business Area css = EditCountryArea(typeI,dataCH[10][1]) driver.find_element(By.ID, css).click() selService = Select(driver.find_element_by_id('customfield_24995')) #Service selService.deselect_by_visible_text('None') selService.select_by_visible_text(dataCH[11][1]) selApp = Select(driver.find_element_by_id('customfield_24924')) #Application selApp.deselect_by_visible_text('None') selApp.select_by_visible_text(dataCH[12][1]) selIPrac = Select(driver.find_element_by_id('customfield_24654')) #Input Practice selIPrac.select_by_visible_text(dataCH[13][1]) selIT = Select(driver.find_element_by_id('customfield_24685')) #Impact Type selIT.select_by_visible_text(dataCH[14][1]) selEnv = Select(driver.find_element_by_id('customfield_24686')) #Environment selEnv.select_by_visible_text(dataCH[15][1]) selRisk = Select(driver.find_element_by_id('customfield_24690')) #Risk selRisk.select_by_visible_text(dataCH[16][1]) selImp = Select(driver.find_element_by_id('customfield_24687')) #Impac selImp.select_by_visible_text(dataCH[17][1]) selUrg = Select(driver.find_element_by_id('customfield_24688')) #Urgency selUrg.select_by_visible_text(dataCH[18][1]) selChC = Select(driver.find_element_by_id('customfield_24691')) #Change Category selChC.select_by_visible_text(dataCH[19][1]) driver.find_element(By.ID, "customfield_24656").click() #Change Reason driver.find_element(By.ID, "customfield_24656").send_keys(dataCH[20][1]) selPA = Select(driver.find_element_by_id('customfield_24655')) #Probability of anomalies selPA.select_by_visible_text(dataCH[21][1]) driver.find_element(By.ID, "customfield_24692").click() #Effect of non-implementation driver.find_element(By.ID, "customfield_24692").send_keys(dataCH[22][1]) driver.find_element(By.ID, "issue-workflow-transition-submit").click() #Submit información Edit driver.implicitly_wait(20) url = driver.current_url estado = "Se creó el cambio correctamente." return estado, url except Exception as error: return "No se creó correctamente el cambio. ", error
def deSelectDropdownByVisibleText(element, value): sel = Select(element) sel.deselect_by_visible_text(value)
def dropdown_deselecbytext(self, element, text): varA = Select(element) varA.deselect_by_visible_text(text)
s.select_by_value("sub1") time.sleep(2) s.select_by_index(3) time.sleep(2) s.select_by_visible_text("Mysore") time.sleep(2) options = s.options print(options) print("all_options are") for i in options: print(i.text) print() selected_options = s.all_selected_options print(selected_options) print("all_selected_options are") for i in selected_options: print(i.text) print() first_selected = s.first_selected_option print("first_selected_option : ", first_selected.text) print() print(s.is_multiple) s.deselect_by_value("sub2") time.sleep(2) s.deselect_by_index(2) time.sleep(2) s.deselect_by_visible_text("Mumbai") time.sleep(2) driver.close()
class ScreeningDrop(action_visible): # ----------------------------------初始化参数------------------------ def __init__(self, drivers, labelPath=None, attr='id'): """ 创建select操作的对象 :param drivers: 浏览器对象 :param labelPath: 元素位置 :param attr: 元素类型:css还是id """ self.drivers = drivers if labelPath: self.setSelectData(labelPath, attr) else: pass def setSelectData(self, labelPath, attr='id'): try: if attr.lower() == 'id': # 找到select元素 selectEle = self.is_visible_id(self.drivers, labelPath) else: selectEle = self.is_visible_css_selectop( self.drivers, labelPath) self.ele_select(selectEle) return self except UnexpectedTagNameException: print("该元素不是select对象:The incoming element path is not a select.") def ele_select(self, selectEle): """ 通过元素来创建下拉对象 :return: """ self.select = Select(selectEle) # 装options的数据,不创建value的容器是因为很少使用value self.optionsList = [] return self # --------------------------------参数类型转换---------------------- def options_to_str(self): self.getAllOptions() str_option = ','.join(self.optionsList) return str_option # ----------------------------------获取参数------------------------ def __getOptions__(self): """ 统计options值,只限内部使用。外部不可调用 :return: """ for option in self.select.options: self.optionsList.append(option.text.strip()) def get_value(self): """ 统计value值,只限内部使用。外部不可调用 :return: """ self.valueList = [] for option in self.select.options: self.valueList.append(option.get_attribute("value").strip()) def getSelector(self): # 返回select对象 return self.select def getSelectedOptions(self) -> str: ''' 返回当前业已选择的option :return: ''' selected = self.select.first_selected_option.text.strip() return selected def getAllOptions(self): """ 获取全部的option数据 :return: 返回全部的option """ if self.optionsList: pass else: self.__getOptions__() pass return self.optionsList def getAllValue(self): """ 获取全部的value数据 :return: 返回全部value """ try: if self.valueList: pass except Exception as e: self.get_value() pass finally: return self.valueList def getOptionsSize(self): """ 先进options页面判断options数据是否存在 然后在执行返回 :return: 返回当前options值的总数 """ self.getAllOptions() return len(self.optionsList) def getValueSize(self): """ 先进去values页面判断values数据是否存在 然后在执行返回 :return: 返回当前options所对应的value值总数 """ self.getAllValue() return len(self.valueList) # ----------------------------------设置选择的参数------------------------ def setSelectorValue(self, value): """ 通过value值来设置selector中的option :param value: 需要设置新的option值所对应的value :return: 返回替换前的option """ try: selected = self.getSelectedOptions() self.select.select_by_value(value) return selected finally: return 'There is no option %s in the select.' % value def setSelectorIndex(self, index): """ 通过index值来设置selector中的option :param index: 需要设置新的option值所对应的index :return: 返回替换前的option """ try: selected = self.getSelectedOptions() self.select.select_by_index(index) return selected finally: return 'There is no option %s in the select.' % index def setSelectorText(self, text) -> str: """ 通过text值来设置selector中的option :param text: 需要设置新的option值所对应的text :return: 返回替换前的option """ try: selected = self.getSelectedOptions() # 判断当前业已的option是否为需要新设置的数据信息 if selected == text: pass else: self.select.select_by_visible_text(text) time.sleep(1) except Exception as a: print( "This parameter is not found in the drop-down box %s --- %s" % (text, a)) finally: return selected # ---------------------------------------遍历设置option值----------------------------- def traverseYield(self, textList): ''' 根据lit/dict创建迭代器 :param textList: :return: ''' for text in textList: yield text def traverseSetText(self, textList): ''' 通过lit/dict来设置select的option :param textList: :return: ''' tr_yield = self.traverseYield(textList) for text in tr_yield: self.select.select_by_visible_text(text) # ----------------------------------取消已选择的参数------------------------ def setDeselectAll(self): """ 取消select中全部业已选择的option :return: 返回取消前的option """ selected = self.getSelectedOptions() self.select.deselect_all() return selected def setDeselectValue(self, value): """ 根据value来取消业已选择的option :param value: 取消option值所对应的value :return:返回取消前的option """ selected = self.getSelectedOptions() self.select.deselect_by_value(value) return selected def setDeselectIndex(self, index): """ 根据index来取消业已选择的option :param index: 取消option值所对应的index :return:返回取消前的option """ selected = self.getSelectedOptions() self.select.deselect_by_index(index) return selected def setDeselectText(self, text): """ 根据text来取消业已选择的option :param text: 取消option值所对应的text :return: 返回取消前的option """ selected = self.getSelectedOptions() self.select.deselect_by_visible_text(text) return selected # -------------------------------根据新的label来设置内容------------------------------ def lable_set_text(self, label, text): ''' 根据label来设置新的text :param label: select位置 :param text: 需要设置的值 :return: ''' self.setSelectData(label) self.setSelectorText(text) time.sleep(0.5)
def deselect_element_by_visibletext(self, webelement, text): sel = Select(webelement) sel.deselect_by_visible_text(text)
def select(self, locator, value): select = Select(self.driver.find_element(*locator)) if isinstance(value, int): select.select_by_index(value) else: select.deselect_by_visible_text(value)
def select_by_visible_text(self, element, visibletext): s = Select(element) s.select_by_visible_text(visibletext) s.deselect_by_visible_text(visibletext)