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_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 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 subcategory(self, subcategory: str): select_category = Select( self.driver.find_element_by_xpath(self.SUBCATEGORY)) if subcategory not in [ o.get_attribute('value') for o in select_category.options ]: select_category.select_by_index(0) else: select_category.deselect_by_value(subcategory)
def clear(self, value=""): if self.__tag == "input" or self.__tag == "textarea": self.__element.clear() elif self.__tag == "select": select = Select(self.__element) if value != None: select.deselect_by_value(value) else: select.deselect_all()
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_value(locatorMethod, locatorExpression, option_value, *args): u"""取消勾选选中项根据value""" global driver try: select = Select(getElement(driver, locatorMethod, locatorExpression)) select.deselect_by_value(option_value) except Exception, e: raise e
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()
class BaseClass: wait = None @staticmethod def get_logger(): logger_name = inspect.stack()[1][3] logger = logging.getLogger(logger_name) fmt = logging.Formatter( "%(asctime)s: %(levelname)s %(name)s: %(message)s") file_handler = logging.FileHandler('../results/sel_automation.log', 'a') file_handler.setFormatter(fmt) logger.addHandler(file_handler) logger.setLevel(logging.INFO) return logger def wait_for_presence(self, locator, wait_time=10): if not BaseClass.wait: BaseClass.wait = WebDriverWait(self.driver, wait_time) BaseClass.wait.until(EC.presence_of_element_located(locator)) def wait_for_window_count(self, window_count, wait_time=10): if not BaseClass.wait: BaseClass.wait = WebDriverWait(self.driver, wait_time) BaseClass.wait.until(EC.number_of_windows_to_be(window_count)) def wait_for_alert(self, wait_time=10): if not BaseClass.wait: BaseClass.wait = WebDriverWait(self.driver, wait_time) BaseClass.wait.until(EC.alert_is_present()) def wait_for_clickable(self, locator, wait_time=10): if not BaseClass.wait: BaseClass.wait = WebDriverWait(self.driver, wait_time) BaseClass.wait.until(EC.element_to_be_clickable(locator)) def select_element(self, locator, select_type, select_value): self.select = Select(self.driver.find_element(*locator)) if select_type == 'visible_text': self.select.select_by_visible_text(select_value) elif select_type == 'index': self.select.select_by_index(select_value) elif select_type == 'value': self.select.deselect_by_value(select_value) else: print("Unsupported Selection Format {}".format(select_type)) def get_select_options(self): return self.select.options def populate_data_source(self, source): if source == "excel": DataProviderClass.populate_data_from_excel() elif source == "json": DataProviderClass.populate_data_from_json()
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 deselectValue(self, idpro, value, selectValue): el = self.webObject.testEle(idpro=idpro, value=value) try: s = Select(el) s.deselect_by_value(selectValue) log.info("取消按value选择,根据对象{0}[{1}],取消选择成功".format(idpro, value)) except AssertionError as e: screenshotdir = saveScreenShot(self.driver) log.error("取消按value选择,根据对象{0}[{1}],取消选择失败,错误截图请见:{2}".format( idpro, value)) raise e
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 select_country_correct(self): assert not self.is_element_present(*JQuerySelectLocators.COUNTRY_LIST), \ "Select Country span present, but should not" select_form = self.browser.find_element( *JQuerySelectLocators.SELECT_COUNTRY_FORM) select_form.click() assert self.is_element_present(*JQuerySelectLocators.COUNTRY_LIST), \ "Select Country span not present, but should " select_country = Select( self.browser.find_element(*JQuerySelectLocators.SELECT_COUNTRY)) select_country.deselect_by_value("Hong Kong") time.sleep(4)
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 __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 test_MultiSelect(self): self.driver.get(self.baseurl2) sel=Select(self.driver.find_element_by_id("fruits")) self.assertEqual(sel.is_multiple, True) sel.select_by_visible_text("Apple") time.sleep(2) sel.deselect_by_value("apple") time.sleep(2) sel.select_by_index(3) sel.select_by_value("orange") print(list(sel.all_selected_options)) time.sleep(2) sel.deselect_all()
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 find_select(self, element, tag=1, index=0, values=None, text=None): ''' 下拉列表方法 :param element: 元素 :param tag: 默认为1 :param index: 下表默认0 :param values: 默认空 :param text: 默认空 :return: ''' select = Select(element) if tag == 1: # 表示所有的option列表里面的属性值 下标控制 select.select_by_index(index) if tag == 2: # 选择下拉列表里面的元素 select.deselect_by_value(values) else: # 获取文本打印属性值信息 return select.select_by_visible_text(text)
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()
selected_element.select_by_value("o2val") print(selected_element.first_selected_option.text) selected_element.select_by_visible_text("o3") print(selected_element.first_selected_option.text) ele2=driver.find_element_by_id("s4Id") selected_element2=Select(ele2) selected_element2.select_by_index(1) selected_element2.select_by_index(2) selected_element2.select_by_index(3) print("######") for select in selected_element2.all_selected_options: print(select.text) print("######") selected_element2.deselect_by_index(1) for select in selected_element2.all_selected_options: print(select.text) print("######") selected_element2.deselect_by_value("o2val") for select in selected_element2.all_selected_options: print(select.text) print("######") selected_element2.deselect_by_visible_text("o3") for select in selected_element2.all_selected_options: print(select.text)
#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 deSelectByValueinDropdown(ele, value): sel = Select(ele) sel.deselect_by_value(value)
def dropdown_deselectbyvalue(self, element, value): varA = Select(element) varA.deselect_by_value(value)
def deSelectDropdownByVal(element, value): sel = Select(element) sel.deselect_by_value(value)
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_value(self, webelement, value): sel = Select(webelement) sel.deselect_by_value(value)