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_option_by_index(locatorMethod, locatorExpression, option_index, *args): u"""取消勾选选中项根据index""" global driver try: select = Select(getElement(driver, locatorMethod, locatorExpression)) select.deselect_by_index(option_index) 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()
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 deselectIndex(self, idpro, value, selectIndex): el = self.webObject.testEle(idpro=idpro, value=value) try: s = Select(el) s.deselect_by_index(selectIndex) log.info("取消按index选择,根据对象{0}[{1}],取消选择成功".format(idpro, value)) except AssertionError as e: screenshotdir = saveScreenShot(self.driver) log.error("取消按index选择,根据对象{0}[{1}],取消选择失败,错误截图请见:{2}".format( idpro, value)) raise e
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 test_multiple_drop_down_menu(self): """Test multiple drop down menu.""" # locators multiple_drop_down = 'multiple-select-example' # steps locate_multiple_drop_down = WebDriverWait(self.driver, 10).until( ec.visibility_of_element_located((By.ID, multiple_drop_down))) # loop through menu elements and select all options and deselect collect_all_options = Select(locate_multiple_drop_down) for element in range(len(collect_all_options.options)): collect_all_options.select_by_index(element) collect_all_options.deselect_by_index(element)
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_login(): dr = webdriver.Chrome() dr.get("https://www.facebook.com/") dr.find_element_by_name("firstname").send_keys("Amul") dr.find_element_by_xpath('//*[@id="u_0_n"]').send_keys("kumar") dr.find_element_by_id('u_0_q').send_keys("*****@*****.**") dr.find_element_by_xpath('//*[@id="u_0_x"]').send_keys('12345678') s = dr.find_element_by_name('day') day= Select(s) day.select_by_value('15') m =dr.find_element_by_xpath('//*[@id="month"]') month =Select(m) month.deselect_by_index('9') y = dr.find_element_by_name('birthday_year') year =Select(y) year.select_by_visible_text('1991')
class SelectElem(BaseElement): def __init__(self, by, locator): super(SelectElem, self).__init__(by, locator) self.select = None def _select_init(self): try: self.select = Select(self._find_element()) except Exception: pass def select_by_index(self, index): self._select_init() self._highlight() self.select.select_by_index(index) def deselect_by_index(self, index): self._select_init() self._highlight() self.select.deselect_by_index(index) def select_by_value(self, value): self._select_init() self._highlight() self.select.select_by_value(value) def get_selected_value(self): self._select_init() self._highlight() return self.select.first_selected_option def get_selected_text(self): self._select_init() self._highlight() return self.select.first_selected_option.text def get_all_options(self): self._select_init() self._highlight() return self.select.options def get_options_count(self): self._select_init() return len(self.select.options)
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 drop_down_multi_select(): url_dropdown = "https://www.seleniumeasy.com/test/basic-select-dropdown-demo.html" driver.get(url_dropdown) ddown_list = driver.find_element_by_id("multi-select") # Select element with '<select>' tag selection = Select(ddown_list) # Multi select drop down enables you to select multi options selection.select_by_value("New York") selection.select_by_visible_text("Ohio") print("selection.all_selected_options :") for element in selection.all_selected_options: print(element.text) # this will return all selected options (new york, ohio) print("Delesecting by index: ") selection.deselect_by_index(4) selection.select_by_index(5) selection.select_by_index(7) print("Deselecting_all : ") selection.deselect_all()
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 test_AllAssingnment(self): self.driver.get("http://cookbook.seleniumacademy.com/Config.html") print(self.driver.title) eselect_class = self.driver.find_element_by_name("make") eselect_selection = Select(eselect_class) eselect_selection.select_by_visible_text("Honda") eselect_selection.select_by_index(1) eselect_selection.select_by_value("audi") time.sleep(2) self.driver.find_element_by_xpath("//input[@value='Diesel']").click() airbags = self.driver.find_element_by_name("airbags") if not airbags.is_selected(): airbags.click() print(airbags.is_enabled()) time.sleep(2) color = Select(self.driver.find_element_by_name("color")) color.select_by_value("bl") color.deselect_by_index(0) color.select_by_visible_text("Silver") time.sleep(2)
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)
from selenium import webdriver from selenium.webdriver.support.select import Select driver=webdriver.Chrome(executable_path="C://Selenium//driver//chromedriver_win32//chromedriver.exe") URL = "http://*****:*****@hotmail.com") driver.find_element_by_id("inputPassword4").send_keys("Alan_Alford63") driver.find_element_by_id("inputAddress").send_keys("3077b Oak Ave") driver.find_element_by_id("inputAddress2").send_keys("Newton Building, Ste 472") driver.find_element_by_id("inputCity").send_keys("Seattle") Options=Select(driver.find_element_by_id('inputgadget')) Options.select_by_index(1) Options.select_by_index(3) driver.find_element_by_id("inputZip").send_keys("WA 98195") Options.deselect_by_index(1) Options.deselect_by_index(3) Options.select_by_index(2) Options.select_by_index(4) print("Test Case Passed : ") except Exception as e: print("Test Case Failed : ")
print("3.Selected option is ", sel.first_selected_option.text) sel.select_by_value("OFFER DECLINED") print("4.Selected option is ", sel.first_selected_option.text) #You can deselect options of a multi-select driver.get( "https://www.jqueryscript.net/demo/Two-side-Multi-Select-Plugin-with-jQuery-multiselect-js/" ) ele = driver.find_element_by_id("undo_redo") sel = Select(ele) print("-----All options--------") for a in sel.options: print(a.text) print("----------------------") print("is it multi select- ", sel.is_multiple) sel.select_by_index(5) print("5.Selected option is ", sel.first_selected_option.text) sel.deselect_by_index(5) print("6.Selected option count is ", len(sel.all_selected_options)) sel.select_by_value("4") sel.select_by_visible_text("PHP") print("7.Selected option count is ", len(sel.all_selected_options)) print("-----All selected options--------") for a in sel.all_selected_options: print(a.text) sel.deselect_all() print("8.Selected option count is ", len(sel.all_selected_options)) driver.quit()
#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 deselect_element_by_index(self, webelement, index): sel = Select(webelement) sel.deselect_by_index()
def dropdown_deselectbyindex(self, element, index): varA = Select(element) varA.deselect_by_index(index)
#将页面滚动条拖到底部 js = "var q=document.documentElement.scrollTop=10000" chomd.execute_script(js) time.sleep(3) #将滚动条移动到页面的顶部 js_ = "var q=document.documentElement.scrollTop=0" chomd.execute_script(js_) time.sleep(3) chomd.implicitly_wait(5) #找不到元素全局等待 chomd.find_element_by_xpath("").click() #xpath chomd.find_element_by_id('').click() #id chomd.find_elements_by_css_selector().click() #css #下拉框 select = Select(chomd.find_elements_by_xpath("")) select.select_by_visible_text("") #文本 select.deselect_by_index() #下标 select.select_by_value("") #value #告警窗 chomd.switch_to_alert().accept() #点击确认 chomd.find_to.alert.accept() #新式点击 #窗口切换 handle = chomd.window_handles #获取句柄 chomd.switch_to.window(handle[1]) #新增页面 # 截图 chomd.maximize_window() current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time())) time.sleep(1) chomd.get_screenshot_as_file("E:\\图片\\" + current_time + '微信扫码' + '.png') chomd.get_screenshot_as_file("D:\\baidu_img.png") #嵌套
def deSelectDropdownByindex(element, index): sel = Select(element) sel.deselect_by_index(index)
#!/usr/bin/env python #@Time :2019-11-01 21:43:17 #@Author :azhenglianxi #@Software :PyCharm #单元框 #怎么判断元素 是不是被选中 from selenium.webdriver.support.select import Select ## male.clock() #来选中元素 # if not bike.is_slelcted(): # bike.click() #复选框 怎么选择 #select 标签的 from Selenium_auto.funtion_Interface import * driver = ChromeDriverBrowser() se = driver.find_element_by_id('') select = Select(se) select.select_by_visible_text('宝马 740') select.deselect_by_index(0) #通过下标选择 从0开始 #全选操作 select.deselect_all() #全部取消选择 select.is_multiple.bit_length() #单选下拉框 select.select_by_visible_text("女")
print("所有的城市选项:") for i in mycity.options: print(i) print(i.text) for j in mycity.all_selected_options: print("目前选中的城市:",j.text) print("===========================") # 是否多选 if mynation.is_multiple ==True: print("民族可以多选") else: print("民族只能单选") # 取消默认被选项 mynation.deselect_by_index(0) # 选择其中的三项 mynation.select_by_index(1) mynation.select_by_value("满族") mynation.select_by_visible_text("哈萨克族") # 列出所有的民族选项 for item1 in mynation.options: print(item1.text) # 列出选择的名族选项 for item2 in mynation.all_selected_options: print(item2.text) # 选中的第一项 first_item = mynation.first_selected_option
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)