def select_multi_items(self, select_name): """ Select multiple options from select with label (recommended), name, or id. Pass a multiline string of options. e.g. .. code-block:: gherkin When I select the following from "Contact Methods": \"\"\" Email Phone Fax \"\"\" """ # Ensure only the options selected are actually selected option_names = self.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) assert select_box, "Cannot find a '{}' select.".format(select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: try: select.select_by_visible_text(option) except NoSuchElementException: raise AssertionError("Cannot find option: '{}'.".format(option))
def fset(self, value): if self.element.tag_name.lower() == 'file': pass # if self.mech_control.type == 'file': # self.mech_control.add_file(value, # content_type=self.content_type, # filename=self.filename) # select elif self.element.tag_name.lower() == 'select': select = Select(self.element) if self.element.get_attribute('multiple'): select.deselect_all() else: value = [value] for opt in select.options: v = opt.get_attribute('value') if v in value: value.remove(v) if not opt.is_selected(): opt.click() if value: raise AttributeError('Options not found: %s' % ','.join(value)) else: # textarea, input type=text self.element.clear() self.element.send_keys(value)
def testDeselectAllMultiple(self, driver, pages): if driver.capabilities['browserName'] == 'chrome' and int(driver.capabilities['version'].split('.')[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() assert len(sel.all_selected_options) == 0
def testDeselectAllMultiple(self): if self.driver.capabilities['browserName'] == 'chrome' and int(self.driver.capabilities['version'].split('.')[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(self.driver.find_element(By.NAME, select['name'])) sel.deselect_all() self.assertEqual(len(sel.all_selected_options), 0)
def callback(elements): s = Select(elements.item) if i is not None: s.deselect_by_index(i) elif value is not None: s.deselect_by_value(value) elif text is not None: s.deselect_by_visible_text(text) else: s.deselect_all()
def testSelectByVisibleTextMultiple(driver, pages): pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() for x in range(len(select['values'])): sel.select_by_visible_text(select['values'][x]) selected = sel.all_selected_options assert len(selected) == x + 1 for j in range(len(selected)): assert selected[j].text == select['values'][j]
def select_multi_items(browser, list, elem): options = [unquote_variable(i.strip()) for i in list.split(",")] select_box = find_element(browser, elem) select = Select(select_box) select.deselect_all() for option in options: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option)
def select_multi_items(self, select_name): # Ensure only the options selected are actually selected option_names = self.multiline.split('\n') select_box = find_field(world.browser, 'select', select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option)
def select_multi_items(test, select_name, option_names): # Ensure only the options selected are actually selected option_names = [on.strip() for on in option_names.split('\n') if on.strip()] select_box = find_field(test.browser, 'select', select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option)
def testSelectByVisibleTextMultiplePartialText(self): if self.driver.capabilities['browserName'] == 'chrome' and int(self.driver.capabilities['version'].split('.')[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") sel = Select(self.driver.find_element(By.NAME, multiSelectValues1['name'])) sel.deselect_all() sel.select_by_visible_text("Onion gr") self.assertEqual(sel.first_selected_option.text, multiSelectValues1['values'][3]) sel = Select(self.driver.find_element(By.NAME, multiSelectValues2['name'])) sel.deselect_all() sel.select_by_visible_text(" ") self.assertEqual(len(sel.all_selected_options), 4)
def select_multi_items(step, select_name): with AssertContextManager(step): # Ensure only the options selected are actually selected option_names = step.multiline.split("\n") select_box = find_field(world.browser, "select", select_name) select = Select(select_box) select.deselect_all() for option in option_names: try: select.select_by_value(option) except NoSuchElementException: select.select_by_visible_text(option)
def testSelectByVisibleTextMultiple(self, driver, pages): if driver.capabilities["browserName"] == "chrome" and int(driver.capabilities["version"].split(".")[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select["name"])) sel.deselect_all() for x in range(len(select["values"])): sel.select_by_visible_text(select["values"][x]) selected = sel.all_selected_options assert len(selected) == x + 1 for j in range(len(selected)): assert selected[j].text == select["values"][j]
def testSelectByIndexMultiple(self, driver, pages): if driver.capabilities['browserName'] == 'chrome' and int(driver.capabilities['version'].split('.')[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() for x in range(len(select['values'])): sel.select_by_index(x) selected = sel.all_selected_options assert len(selected) == x + 1 for j in range(len(selected)): assert selected[j].text == select['values'][j]
def testSelectByVisibleTextMultiple(self): if self.driver.capabilities['browserName'] == 'chrome' and int(self.driver.capabilities['version'].split('.')[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(self.driver.find_element(By.NAME, select['name'])) sel.deselect_all() for x in range(len(select['values'])): sel.select_by_visible_text(select['values'][x]) selected = sel.all_selected_options self.assertEqual(len(selected), x+1) for j in range(len(selected)): self.assertEqual(selected[j].text, select['values'][j])
def testDeselectByVisibleTextMultiple(driver, pages): pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() sel.select_by_index(0) sel.select_by_index(1) sel.select_by_index(2) sel.select_by_index(3) sel.deselect_by_visible_text(select['values'][1]) sel.deselect_by_visible_text(select['values'][3]) selected = sel.all_selected_options assert len(selected) == 2 assert selected[0].text == select['values'][0] assert selected[1].text == select['values'][2]
def select_dropDownBox_by_texts(self, element, texts): """ 适用多选下拉框 :param webElement: :param texts:以数组传参 :return: """ if isinstance(element, ElementInfo): webElement = Select(self.getElement(element)) elif isinstance(element, WebElement): webElement = Select(element) else: return None webElement.deselect_all() for text in texts: webElement.select_by_visible_text(text)
def testSelectByVisibleTextMultiple(self): if self.driver.capabilities['browserName'] == 'chrome' and int( self.driver.capabilities['version'].split('.')[0]) < 16: pytest.skip( "deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(self.driver.find_element(By.NAME, select['name'])) sel.deselect_all() for x in range(len(select['values'])): sel.select_by_visible_text(select['values'][x]) selected = sel.all_selected_options self.assertEqual(len(selected), x + 1) for j in range(len(selected)): self.assertEqual(selected[j].text, select['values'][j])
def testSelectByVisibleTextMultiple(self, driver, pages): if driver.capabilities['browserName'] == 'chrome' and int( driver.capabilities['version'].split('.')[0]) < 16: pytest.skip( "deselecting preselected values only works on chrome >= 16") pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() for x in range(len(select['values'])): sel.select_by_visible_text(select['values'][x]) selected = sel.all_selected_options assert len(selected) == x + 1 for j in range(len(selected)): assert selected[j].text == select['values'][j]
def select_dropDownBox_by_indexs(self, element, indexs): """ 适用多选下拉框,下标从0开始 :param webElement: :param indexs: 以数组传参 :return: """ if isinstance(element, ElementInfo): webElement = Select(self.getElement(element)) elif isinstance(element, WebElement): webElement = Select(element) else: return None webElement.deselect_all() for index in indexs: webElement.select_by_index(index)
def select_dropDownBox_by_values(self, element, values): """ 适用多选下拉框 :param webElement: :param values:以数组传参 :return: """ if isinstance(element, ElementInfo): webElement = Select(self.getElement(element)) elif isinstance(element, WebElement): webElement = Select(element) else: return None webElement.deselect_all() for value in values: webElement.select_by_value(value)
def testDeselectByValueMultiple(self, driver, pages): if driver.capabilities["browserName"] == "chrome" and int(driver.capabilities["version"].split(".")[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select["name"])) sel.deselect_all() sel.select_by_index(0) sel.select_by_index(1) sel.select_by_index(2) sel.select_by_index(3) sel.deselect_by_value(select["values"][1].lower()) sel.deselect_by_value(select["values"][3].lower()) selected = sel.all_selected_options assert len(selected) == 2 assert selected[0].text == select["values"][0] assert selected[1].text == select["values"][2]
def testDeselectByVisibleTextMultiple(self, driver, pages): if driver.capabilities['browserName'] == 'chrome' and int(driver.capabilities['version'].split('.')[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() sel.select_by_index(0) sel.select_by_index(1) sel.select_by_index(2) sel.select_by_index(3) sel.deselect_by_visible_text(select['values'][1]) sel.deselect_by_visible_text(select['values'][3]) selected = sel.all_selected_options assert len(selected) == 2 assert selected[0].text == select['values'][0] assert selected[1].text == select['values'][2]
def testSelectByValueMultiple(self): if ( self.driver.capabilities["browserName"] == "chrome" and int(self.driver.capabilities["version"].split(".")[0]) < 16 ): pytest.skip("deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(self.driver.find_element(By.NAME, select["name"])) sel.deselect_all() for x in range(len(select["values"])): sel.select_by_value(select["values"][x].lower()) selected = sel.all_selected_options self.assertEqual(len(selected), x + 1) for j in range(len(selected)): self.assertEqual(selected[j].text, select["values"][j])
def select_dropDownBox_by_values(self, element, values, highlight_seconds=5): """ 适用多选下拉框 :param element: :param values:以数组传参 :return: """ webElement = self._change_element_to_webElement_type( element, highlight_seconds) if webElement: webElement = Select(webElement) webElement.deselect_all() for value in values: webElement.select_by_value(value)
def select_dropDownBox_by_indexs(self, element, indexs, highlight_seconds=5): """ 适用多选下拉框,下标从0开始 :param element: :param indexs: 以数组传参 :return: """ webElement = self._change_element_to_webElement_type( element, highlight_seconds) if webElement: webElement = Select(webElement) webElement.deselect_all() for index in indexs: webElement.select_by_index(index)
def test_datawarehouse_diatic14feb2016(self): driver = self.driver driver.get(self.base_url) driver.find_element_by_link_text("UNICAL 2.1.0").click() driver.find_element_by_id("Uid").clear() driver.find_element_by_id("Uid").send_keys(username) driver.find_element_by_id("Pwd").clear() driver.find_element_by_id("Pwd").send_keys(password) driver.find_element_by_id("3054").click() driver.find_element_by_css_selector("div.name > a.mstr-link").click() driver.find_element_by_link_text("REPORT ASTISS").click() driver.find_element_by_link_text("Riesame").click() driver.find_element_by_link_text( "Esami per coorte di immatricolazione e studente con anno accademico sostenimento" ).click() time.sleep(1) select_co_im = Select(driver.find_element_by_id("unitsToAdd")) select_co_im.deselect_all() print 'Coorti di immatricolazione disponibili:' for i in select_co_im.options: print i.text select_co_im.select_by_visible_text(nome_coorte) # clicco per selezionare #driver.find_elements(By.CLASS_NAME, "cheese") driver.find_element_by_id("addUnitsButton").click() select_cdl = Select(driver.find_element_by_id("unitsToAdd_1")) select_cdl.deselect_all() time.sleep(1) print 'Corsi di laurea disponibili:' for i in select_cdl.options: print i.text select_cdl.select_by_visible_text(corso_di_laurea) time.sleep(1) driver.find_element_by_id("addUnitsButton_1").click() driver.find_element_by_id("answerButton").click() element = WebDriverWait(driver, 120).until( EC.presence_of_element_located((By.ID, "tbExport"))) element.click() #driver.find_element_by_id("tbExport").click() time.sleep(9) driver.get(self.base_url + '/Main.aspx?evt=3008&src=Main.aspx.3008')
def testDeselectByValueMultiple(self): if self.driver.capabilities['browserName'] == 'chrome' and int(self.driver.capabilities['version'].split('.')[0]) < 16: pytest.skip("deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(self.driver.find_element(By.NAME, select['name'])) sel.deselect_all() sel.select_by_index(0) sel.select_by_index(1) sel.select_by_index(2) sel.select_by_index(3) sel.deselect_by_value(select['values'][1].lower()) sel.deselect_by_value(select['values'][3].lower()) selected = sel.all_selected_options self.assertEqual(len(selected), 2) self.assertEqual(selected[0].text, select['values'][0]) self.assertEqual(selected[1].text, select['values'][2])
def test_operateMultipleOptionDropList(self): url = 'F:\\HTMLTest\\select.html' self.driver.get(url) select_element = Select(self.driver.find_element_by_xpath('//select')) select_element.select_by_index(0) select_element.select_by_visible_text('山楂') select_element.select_by_value('mihoutao') for option in select_element.all_selected_options: print(option.text) select_element.deselect_all() time.sleep(2) print('---------------- 再次选中 3 个选项 ------------------') select_element.select_by_index(1) select_element.select_by_visible_text('荔枝') select_element.select_by_value('juzi') select_element.deselect_by_visible_text('荔枝') select_element.deselect_by_index(1) select_element.deselect_by_value('juzi')
def _set_multiple_select_values(self, values, clear_current_value=False): """Select one or more options in a multiple select element :param values: List of ``value`` attributes for the options to select (or a single ``value`` attribute if only one needs to be selected) :param clear_current_value: (Default = False) if True, deselect any currently selected options before selecting the new ones """ select = Select(self.find_input_element()) if clear_current_value: select.deselect_all() # If values is just a single item, make it a list with just itself to # avoid any iteration issues (e.g. if it's a string) if not isinstance(values, (list, dict)): values = [values] # TODO: validate value using self.options for value in values: select.select_by_value(value)
def testOperateMultiDropdownlist(self): driver = self.driver WebSite = os.path.join(os.path.abspath('..'), 'Html', '10.23.html') driver.get(WebSite) time.sleep(2) #等待2秒 from selenium.webdriver.support.ui import Select #导入Select模块 Dropdownlist = Select( driver.find_element_by_xpath("//select")) #用xpath方法定位多选下拉列表 time.sleep(2) Dropdownlist.select_by_index(0) #使用select_by_index()方法,通过序号选择第一个元素 time.sleep(2) Dropdownlist.select_by_visible_text( 'Jenson Button' ) #使用select_by_visible_text()方法,通过选项的文本选择"Jenson Button" time.sleep(2) Dropdownlist.select_by_value( 'Ham') #使用select_by_value()方法,通过选项的value值'Ham',选择"Lewis Hamilton" time.sleep(2) for MyDriver in Dropdownlist.all_selected_options: #遍历循环,利用all_selected_options方法,打印所有已经被选中的选项 print(MyDriver.text) time.sleep(2) Dropdownlist.deselect_all() #使用deselect_all()方法,取消选择所有已选中的内容 time.sleep(2) Dropdownlist.select_by_index(1) #随意选择三个选项 Dropdownlist.select_by_visible_text('Sebastian Vettel') Dropdownlist.select_by_value('Rai') time.sleep(2) Dropdownlist.deselect_by_index( 1) #使用deselect_by_index()方法,通过序号取消选择第二个元素 Dropdownlist.deselect_by_visible_text( 'Sebastian Vettel' ) #使用deselect_by_visible_text()方法,通过选项的文本取消选择"Sebastian Vettel" Dropdownlist.deselect_by_value( 'Rai' ) #使用deselect_by_value()方法,通过选项的value值'Rai',取消选择"Kimi Raikkonen" time.sleep(2)
def testDeselectByValueMultiple(self, driver, pages): if driver.capabilities['browserName'] == 'chrome' and int( driver.capabilities['version'].split('.')[0]) < 16: pytest.skip( "deselecting preselected values only works on chrome >= 16") pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() sel.select_by_index(0) sel.select_by_index(1) sel.select_by_index(2) sel.select_by_index(3) sel.deselect_by_value(select['values'][1].lower()) sel.deselect_by_value(select['values'][3].lower()) selected = sel.all_selected_options assert len(selected) == 2 assert selected[0].text == select['values'][0] assert selected[1].text == select['values'][2]
def testSelectByVisibleTextMultiplePartialText(self): if self.driver.capabilities['browserName'] == 'chrome' and int( self.driver.capabilities['version'].split('.')[0]) < 16: pytest.skip( "deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") sel = Select( self.driver.find_element(By.NAME, multiSelectValues1['name'])) sel.deselect_all() sel.select_by_visible_text("Onion gr") self.assertEqual(sel.first_selected_option.text, multiSelectValues1['values'][3]) sel = Select( self.driver.find_element(By.NAME, multiSelectValues2['name'])) sel.deselect_all() sel.select_by_visible_text(" ") self.assertEqual(len(sel.all_selected_options), 4)
def test_operateMultipleOptionDropList(self): url = "file:///C:/Users/Administrator/Desktop/seleniumTestCase/23test.html" self.driver.get(url) from selenium.webdriver.support.ui import Select select_element = Select(self.driver.find_element_by_xpath("//select")) select_element.select_by_visible_text("shanzha") select_element.select_by_value("mihoutao") for option in select_element.select.all_selected_options: print option.text select_element.deselect_all() time.sleep(2) print "----3----" select_element.select_by_index() select_element.select_by_visible_text("lizhi") select_element.select_by_value("juzi") select_element.deselect_by_visible_text("lizhi") select_element.deselect_by_index(1) select_element.deselect_by_value("juzi") time.sleep(3)
def testDeselectByVisibleTextMultiple(self): if ( self.driver.capabilities["browserName"] == "chrome" and int(self.driver.capabilities["version"].split(".")[0]) < 16 ): pytest.skip("deselecting preselected values only works on chrome >= 16") self._loadPage("formPage") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(self.driver.find_element(By.NAME, select["name"])) sel.deselect_all() sel.select_by_index(0) sel.select_by_index(1) sel.select_by_index(2) sel.select_by_index(3) sel.deselect_by_visible_text(select["values"][1]) sel.deselect_by_visible_text(select["values"][3]) selected = sel.all_selected_options self.assertEqual(len(selected), 2) self.assertEqual(selected[0].text, select["values"][0]) self.assertEqual(selected[1].text, select["values"][2])
def main(): # Select Fall 2019 in form sel_term = Select(driver.find_elements_by_name("term_code")[0]) sel_term.select_by_value("201909") # Continues to next page with Fall 2019 Term button = driver.find_element_by_xpath("//input[@type='submit']") button.submit() # Used to get total number of subjects sel_subject = Select(driver.find_elements_by_name("sel_subj")[1]) # Iterate through every index in subject for x in range(1, len(sel_subject.options)): # Select subject sel_subject = Select(driver.find_elements_by_name("sel_subj")[1]) sel_subject.select_by_index(x) sel_subject.deselect_by_index('0') # Select Abbotsford Campus sel_campus = Select(driver.find_elements_by_name("sel_camp")[1]) sel_campus.deselect_all() sel_campus.select_by_visible_text("Abbotsford") # Submit form button2 = driver.find_elements_by_xpath("//input[@type='submit']")[0] button2.submit() # If no courses in subject do not scrape if len(driver.find_elements_by_xpath( "//span[@class='warningtext']")) != 0: print("No courses here!") return_to_subjects() continue # Calls function to scrape all course data scrape_page() # Once complete, return back to course selection return_to_subjects()
def set_field(self, webelement, field_value, append=False): field_tag = webelement.tag_name if field_tag == 'textarea' or \ (field_tag == 'input' and \ webelement.get_attribute('type') not in ['radio','checkbox'] ): webelement.click() if not append: webelement.clear() webelement.send_keys(field_value) #self.find('tag=body').click() elif field_tag == 'input': webelement.click() elif field_tag == 'select': select_element = Select(webelement) if isinstance(field_value, str): select_element.select_by_visible_text(field_value) elif isinstance(field_value, list): if (len(field_value) > 1 and not append) or len(field_value) == 0: select_element.deselect_all() for item in field_value: select_element.select_by_visible_text(str(item))
def _download(self, username, password): from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.options import Options # load the start page self.driver.get(TIMETABLE) # log in self.driver.find_element_by_name("tUserName").send_keys(username) self.driver.find_element_by_name("tPassword").send_keys(password) self.driver.find_element_by_name("bLogin").click() # go to web timetables self.driver.find_element_by_id("LinkBtn_mystudentset").click() # select options from drop downs select = Select(self.driver.find_element_by_id("lbWeeks")) select.deselect_all() select.select_by_visible_text('*All Term Time') select = Select(self.driver.find_element_by_id("lbDays")) select.deselect_all() select.select_by_visible_text('All Week') select = Select(self.driver.find_element_by_id("dlPeriod")) select.select_by_visible_text('All Day (08:00 - 22:00)') select = Select(self.driver.find_element_by_id("dlType")) select.select_by_visible_text('List Timetable (with calendar dates)') # actually get the calendar self.driver.find_element_by_id("bGetTimetable").click() # gets page source source = self.driver.page_source self.driver.quit() return source
def submit_job_SYFPEITHI(peptide_sequence, peptide_length,HLA_Class): # defines the function which inputs into SYFPEITHI # Peptide Sequence takes a String # Peptide Length an Int which must be one of the options on the website # HLA-Class must be the exact text of an option on the dropdown menu. Consider just hard coding this to be our targets of interest # find the text area to enter peptide sequence the hard coded sequence seqelem = driver.find_element_by_name("SEQU") seqelem.clear() seqelem.send_keys(peptide_sequence) seqelem.send_keys(Keys.RETURN) # find the sequence length and set it to that value lengthelem = Select(driver.find_element_by_name("amers")) lengthelem.select_by_value(peptide_length) # find HLA Class element and select the hard coded HLA class HLAclasselem = Select(driver.find_element_by_name("Motif")) HLAclasselem.deselect_all() HLAclasselem.select_by_visible_text(HLA_Class) #HLAclasselem.send_keys(Keys.RETURN) # click Submit submitbutton = driver.find_element_by_name("DoIT") submitbutton.click()
select.select_by_visible_text("text") select.select_by_value(value) # get all available options options = select.options # select all select = Select(driver.find_element_by_xpath("...")) all_selected_options = select.all_selected_options # send for all elems element.submit() # for deselecting elem = Select(driver.find_element_by_id('id')) elem.deselect_all() # find many same elements on page same_elems = driver.find_elements(By.CLASS_NAME, "class_name") # text_field , for example # find element by CSS selector elem = driver.find_element_by_css_selector("input[value=some_name]") # ActionChains cases # for copy img to computer memory (like CTRL+C buttons) action = ActionChains(driver) action.key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform() # Waits # wait some time for download a page or some elements
browser = webdriver.Firefox(firefox_profile=fp) browser.set_window_size(500, 300) browser.set_window_position(200, 200) output_path = dc.locate_raw_observations_folder() / SITE_NAME # ---------------- SCRAPING ---------------- # Load the search webpage for family in families: print("Loading atlas...") browser.get("http://www.oregonflora.org/atlas.php") scraping.wait_for_load(browser, "ID", "btnInstructions") print("Selecting options for " + family + "...") family_select = Select(browser.find_element_by_id("familySelectionBox")) family_select.deselect_all() family_select.select_by_value(family) # Pick the right checkboxes browser.find_element_by_id("Observations").click() browser.find_element_by_id("OSU").click() # Open the advanced options menu browser.find_element_by_id("btnAdvanced").click() scraping.wait_for_load(browser, "ID", "startyear") # Type in correct start year start_year = browser.find_element_by_id("startyear") for i in range(6): # Delete whatever is already there start_year.send_keys(Keys.BACK_SPACE)
def select_option(self, obj): # Set local parameters step = obj.get('order') identifier_dict = obj.get('identifier') if identifier_dict is None: raise Exception('No identifier') child_window = obj.get('child_window') if child_window is None: raise Exception('No child_window') selection_value = obj.get('selection_value') if selection_value is None: raise Exception('No selection_value') selection_type = obj.get('selection_type') if selection_type is None: raise Exception('No selection_type') multiline = obj.get('multiline') action = None element = self.ei.uniquely_identify_element(identifier_dict) # Report no element found if element is None: action = 'No element found' return action if element is not None: # Prepare element for action self.__wait_for_post_back_to_complete(element, obj.get('timeout')) self.driver.execute_script('return arguments[0].scrollIntoView();', element) self.driver.execute_script(' window.scrollBy(0, -100);') selection = Select(element) options = selection.options acted_upon_options = self.__determine_acted_upon_option(options, selection_value, selection_type) # Determine how we are interacting with the select if selection_type.lower() == "index": action = "Select '" + acted_upon_options + "' from the '" + str( self.find_html_for(element.get_attribute('id'))) + "' dropdown" selection.select_by_index(selection_value) elif selection_type.lower() == "text": action = "Select '" + acted_upon_options + "' from the '" + str( self.find_html_for(element.get_attribute('id'))) + "' dropdown" selection.select_by_visible_text(selection_value) elif selection_type.lower() == "value": action = "Select '" + acted_upon_options + "' from the '" + str( self.find_html_for(element.get_attribute('id'))) + "' dropdown" selection.select_by_value(selection_value) elif selection_type.lower() == "deindex": action = "Deselect '" + acted_upon_options + "' from the '" + str( self.find_html_for(element.get_attribute('id'))) + "' dropdown" selection.deselect_by_index(selection_value) elif selection_type.lower() == "detext": action = "Deselect '" + acted_upon_options + "' from the '" + str( self.find_html_for(element.get_attribute('id'))) + "' dropdown" selection.deselect_by_visible_text(selection_value) elif selection_type.lower() == "devalue": action = "Deselect '" + acted_upon_options + "' from the '" + str( self.find_html_for(element.get_attribute('id'))) + "' dropdown" selection.deselect_by_value(selection_value) elif selection_type.lower == "deall": action = "Deselected all values from the '" + str( self.find_html_for(element.get_attribute('id'))) + "' dropdown" selection.deselect_all() else: # This should really just be reported and not raise an exception raise Exception("Unknown selection type.") # Determine if action changes browser count if child_window: self.change_window_connection() print(action) return action
find_element_by_tag_name find_element_by_class_name find_element_by_css_selector # write some text element.send_keys("some text") # select from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_name('name')) select.select_by_index(index) select.select_by_visible_text("text") select.select_by_value(value) select = Select(driver.find_element_by_id('id')) select.deselect_all() ## ## Extract after loading ## from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from pyvirtualdisplay import Display def getElementValue(driver, search_type, css_class): try: if search_type == By.CLASS_NAME:
class Select(BaseElement): """ A web select """ def __init__(self, element): BaseElement.__init__(self, element) self._select = WDSelect(self._element) @property def options(self): """ obtains all options in the select element :return: all options in the select element :rtype: list """ inner_options = self._select.options options = [] for option_se in inner_options: options.append(selenium_web_element_to_element(option_se)) return options @property def selected_options(self): """ obtains all options selected :return: all options selected in the select element :rtype: list """ inner_options = self._select.all_selected_options options = [] for option_se in inner_options: options.append(selenium_web_element_to_element(option_se)) return options @property def first_selected_option(self): """ obtains the first option selected :return: the first option selected in the select element :rtype: BaseElement """ option = self._select.first_selected_option return selenium_web_element_to_element(option) def select_by_index(self, index): """ Selects an option by its index :param index: the index to be searched """ return self._select.select_by_index(index) def select_by_value(self, value): """ Selects an option by its value :param value: the value to be searched """ return self._select.select_by_value(value) def select_by_visible_text(self, text): """ Selects an option by its visible text :param text: the value to be searched """ return self._select.select_by_visible_text(text) def deselect_all(self): """ Deselects all selected options """ self._select.deselect_all() def deselect_by_index(self, index): """ Deselects an option by its index :param index: the index to be searched """ self._select.deselect_by_index(index) def deselect_by_value(self, value): """ Selects an option by its value :param value: the value to be searched """ self._select.deselect_by_value(value) def deselect_by_visible_text(self, text): """ Deselects an option by its visible text :param text: the value to be searched """ self._select.deselect_by_visible_text(text)
def testDeselectAllMultiple(self): self._loadPage("formPage") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(self.driver.find_element(By.NAME, select['name'])) sel.deselect_all() self.assertEqual(len(sel.all_selected_options), 0)
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.support.ui import Select driver = webdriver.Chrome() driver.get("file:///D:/selenium_pages/form_web_element.html") selectEle = Select(driver.find_element_by_id("ss_multi")) selectEle.deselect_all() selectEle.select_by_value("小雷老师")
from selenium import webdriver wd = webdriver.Chrome(r'D:\develop_study\chromedriver\chromedriver') wd.implicitly_wait(5) wd.get('http://cdn1.python3.vip/files/selenium/test2.html') # 导入Select类 from selenium.webdriver.support.ui import Select # 创建Select对象 select = Select(wd.find_element_by_id("ss_multi")) # 清除所有 已经选中 的选项 select.deselect_all() # 选择小雷老师 和 小凯老师 select.select_by_visible_text("小雷老师") select.select_by_visible_text("小凯老师")
state_tree = {} # get all state values state_mselect = Select(driver.find_element_by_css_selector('select[name="admin_state_mselect"]')) for opt in state_mselect.options[1:]: # skip first one 'cause it's crap state_id = opt.get_attribute("value") name = opt.text.split(" - ")[1] # print "%s, %s" % (name, state_id) state_tree[state_id] = {"name": name, "counties": []} for state_id in sorted(state_tree.keys()): print "state %s:" % state_id # set that state state_mselect = Select(driver.find_element_by_css_selector('select[name="admin_state_mselect"]')) state_mselect.deselect_all() state_mselect.select_by_value(state_id) # open county section set_county = driver.find_element_by_css_selector('input[name="county_selectBox"]') set_county.click() # enumerate counties county_mselect = Select(driver.find_element_by_css_selector('select[name="county_mselect"]')) for opt in county_mselect.options[1:]: # first one is crap county_id = opt.get_attribute("value") county_name = opt.text.split(" - ")[1] state_tree[state_id]["counties"].append({ "id": county_id, "name": county_name, })
def _deselect_function(step, pick, find_pattern): ele = _get_visible_element(finder_function, pick, find_pattern) select = Select(ele) select.deselect_all()
#操作输入框 driver.get('https://www.baidu.com/') inputTag = driver.find_element_by_id('kw') inputTag.send_keys('python') time.sleep(5) inputTag.clear() #清除输入框内容 #操作checkbox勾选框 driver.get('https://www.douban.com/') inputTag1 = driver.find_element_by_name('remember') inputTag1.click() #选中checkbox框,取消选中调用两次click #操作select标签 driver.get('http://www.dobai.cn/') select = Select(driver.find_element_by_name('jumpMenu')) select.select_by_index(1) #根据索引值选择页面 select.select_by_value('http://m.95xiu.com/') #根据value值跳转页面 select.select_by_visible_text('95秀') #根据可见文本选择页面 select.deselect_all() #取消所有选中 #操作按钮的点击事件 driver.get('https://www.baidu.com/') inputTag2 = driver.find_element_by_id('kw') inputTag2.send_keys('python') #输入关键词 submitTag = driver.find_element_by_id('su') submitTag.click() #点击按钮
def deselect_all(self, selector): select = Select(self.browser.find_element_by_css_selector(selector)) select.deselect_all() time.sleep(3)
driver.get('https://texas.reserveworld.com/') time.sleep(5) # Let the user actually see something! search_box = driver.find_element_by_name('ctl00$TopMenu1$btnContinueMenu') search_box.submit() time.sleep(5) # Let the user actually see something! park_select = Select( driver.find_element_by_name('ctl00$ContentPlaceHolder1$lstParks')) park_values = [ int(i) for i in [opt.get_attribute("value") for opt in park_select.options] ] for park_id in park_values[24:]: park_select = Select( driver.find_element_by_name('ctl00$ContentPlaceHolder1$lstParks')) park_select.deselect_all() park_select.select_by_value(str(park_id)) driver.find_element_by_name('ctl00$ContentPlaceHolder1$btnSearch').click() loc = park_location(park_id) time.sleep(10) try: table = driver.find_element_by_id( "ctl00_ContentPlaceHolder1_ParksList") info = [] for row in table.find_elements_by_tag_name('tr'): cell = row.find_elements_by_tag_name("td") vals = [ i or "" for i in [ c.text if (c and c.text and len(c.text) > 0 ) else c.get_attribute('onclick') for c in cell ]
def descargarTablas(): driver = getDriver() time.sleep(5) # Seleccionado años yers = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/div/table/tbody/tr/td/div[1]/select" ) yearsValues = yers.find_elements_by_tag_name("option") # for i in range(len(yearsValues)): for i in range(1): yers = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/div/table/tbody/tr/td/div[1]/select" ) yearsValues = yers.find_elements_by_tag_name("option") selectYears = Select(yers) selectYears.deselect_all() yearsValues[i].click() time.sleep(1) print(yearsValues[i].text) # Seleccionado regiones region = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[1]/div/table/tbody/tr[2]/td[1]/div/table/tbody/tr/td/div[1]/select" ) yearsRegion = region.find_elements_by_tag_name("option") for j in range(len(yearsRegion)): # for j in range(1): region = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[1]/div/table/tbody/tr[2]/td[1]/div/table/tbody/tr/td/div[1]/select" ) yearsRegion = region.find_elements_by_tag_name("option") selectRegion = Select(region) selectRegion.deselect_all() yearsRegion[j].click() time.sleep(1) print(yearsRegion[i].text) # Seleccionado tipo de establecimiento stableType = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[1]/div/table/tbody/tr/td/div[1]/select" ) yearsStableType = stableType.find_elements_by_tag_name("option") for k in range(len(yearsStableType)): # for k in range(1): stableType = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[1]/div/table/tbody/tr/td/div[1]/select" ) yearsStableType = stableType.find_elements_by_tag_name( "option") selectStableType = Select(stableType) selectStableType.deselect_all() yearsStableType[k].click() time.sleep(1) print(yearsStableType[i].text) # Seleccionado establecimiento stable = stableType = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[3]/div/table/tbody/tr[2]/td/div/table/tbody/tr/td/div[1]/select" ) yearsStable = stable.find_elements_by_tag_name("option") for l in range(len(yearsStable)): # for l in range(1): stable = stableType = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[3]/div/table/tbody/tr[2]/td/div/table/tbody/tr/td/div[1]/select" ) yearsStable = stable.find_elements_by_tag_name("option") selectStable = Select(stable) selectStable.deselect_all() yearsStable[l].click() time.sleep(1) print(yearsStable[i].text) boton = driver.find_elements_by_tag_name("button") boton[0].click() time.sleep(20) # Descargando tablas yers = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/div/table/tbody/tr/td/div[1]/select" ) yearsValues = yers.find_elements_by_tag_name("option") region = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[1]/div/table/tbody/tr[2]/td[1]/div/table/tbody/tr/td/div[1]/select" ) yearsRegion = region.find_elements_by_tag_name("option") stableType = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[1]/div/table/tbody/tr/td/div[1]/select" ) yearsStableType = stableType.find_elements_by_tag_name( "option") stable = stableType = driver.find_element_by_xpath( "/html/body/form[1]/table/tbody/tr[3]/td/div/div[1]/table/tbody/tr/td/div[2]/div/div[2]/table/tbody/tr[2]/td[3]/div/table/tbody/tr[2]/td/div/table/tbody/tr/td/div[1]/select" ) yearsStable = stable.find_elements_by_tag_name("option") tabla = driver.find_elements_by_class_name("xt") nombreArchivo = yearsValues[i].text + "_" + yearsRegion[ j].text + "_" + yearsStableType[ k].text + "_" + yearsStable[l].text + ".csv" try: saveCSV(tabla, yearsValues[i].text, yearsRegion[j].text, yearsStableType[k].text, yearsStable[l].text, nombreArchivo) print("Datos descargados correctamente.") except: print("No se guardó el archivo.") driver.close()
def testDeselectAllMultiple(driver, pages): pages.load("formPage.html") for select in [multiSelectValues1, multiSelectValues2]: sel = Select(driver.find_element(By.NAME, select['name'])) sel.deselect_all() assert len(sel.all_selected_options) == 0
def _this_step(step, element_name): page_element = get_visible_page_element(element_name) select = Select(page_element) select.deselect_all()
class Select(Action): def __init__(self, driver, locator=None, element=None, wait_time=10, visible=False): super().__init__(driver, locator, element, wait_time, visible) self.dropdown = Select_(self.element) def select_all(self): all_elements = self.dropdown.options if not all_elements: return for ele in all_elements: if not ele.is_selected(): ele.click() def select_by_visible_texts(self, values=""): values = self._convert(values) for value in values: self.dropdown.select_by_visible_text(value) return self def select_by_indices(self, indices): indices = self._convert(indices) for index in indices: self.dropdown.select_by_index(index) return self def select_by_values(self, values=""): values = self._convert(values) for value in values: self.dropdown.select_by_value(value) return self def deselect_all(self): self.dropdown.deselect_all() def deselect_by_visible_texts(self, values=""): values = self._convert(values) for value in values: self.dropdown.deselect_by_visible_text(value) return self def deselect_by_indices(self, indices): indices = self._convert(indices) for index in indices: self.dropdown.deselect_by_index(index) return self def deselect_by_values(self, values=""): values = self._convert(values) for value in values: self.dropdown.deselect_by_value(value) return self @property def options_text(self): #get can be text, value, element all_elements = self.dropdown.options results = self._get_options(all_elements, "text") return results @property def options_value(self): #get can be text, value, element all_elements = self.dropdown.options results = self._get_options(all_elements, "value") return results @property def options_element(self): #get can be text, value, element all_elements = self.dropdown.options results = self._get_options(all_elements, "element") return results @property def all_selected_options_text(self): #get can be text, value, element all_elements = self.dropdown.all_selected_options results = self._get_options(all_elements, "text") return results @property def all_selected_options_value(self): #get can be text, value, element all_elements = self.dropdown.all_selected_options results = self._get_options(all_elements, "value") return results @property def all_selected_options_element(self): #get can be text, value, element all_elements = self.dropdown.all_selected_options results = self._get_options(all_elements, "element") return results def _get_options(self, all_elements, get): results = [] if not all_elements: return results if "text" in get.strip().lower(): for ele in all_elements: results.append(ele.text) elif "value" in get.strip().lower(): for ele in all_elements: results.append(ele.get_attribute('value')) elif "element" in get.strip().lower(): results = all_elements else: get_logger().error("Invalid input. Valid values for get - text, value, element") raise InvalidArgumentError("Invalid input. Valid values for get - text, value, element") return results def _convert(self, values): if not values: values = [] if not isinstance(values, list): values = [values] return values
def find_avail_classes(event = None, context = None): user = occreds.USERNAME user_pass = occreds.PASSWORD # options = Options() # driver = webdriver.Firefox(options=options, executable_path=GECKODIRVER) driver.get(BU_BRAIN_URL) username = driver.find_element_by_id("UserID") password = driver.find_element_by_name("PIN") username.send_keys(user) password.send_keys(user_pass) login_button = driver.find_element_by_xpath("/html/body/div[3]/form/p/input") login_button.click() # time.sleep(5) try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH,"/html/body/div[3]/table[2]/tbody/tr[5]/td[2]/a"))) finally: print('found') # print("poopoo") # sub = R"submenulinktext2" # print(driver.page_source.encode("utf-8")) student_button = driver.find_element_by_xpath("/html/body/div[3]/table[2]/tbody/tr[5]/td[2]/a") student_button.click() try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH,"/html/body/div[3]/table[1]/tbody/tr[1]/td[2]/a"))) finally: print('found') registration_button = driver.find_element_by_xpath("/html/body/div[3]/table[1]/tbody/tr[1]/td[2]/a") registration_button.click() try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH,'/html/body/div[3]/table[1]/tbody/tr[5]/td[2]/a'))) finally: print('found') class_lookup = driver.find_element_by_xpath('/html/body/div[3]/table[1]/tbody/tr[5]/td[2]/a') class_lookup.click() try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH,'//*[@id="term_input_id"]'))) finally: print('found') pick_term = driver.find_element_by_xpath('//*[@id="term_input_id"]') pick_term.click() select = Select(driver.find_element_by_xpath('//*[@id="term_input_id"]')) select.select_by_visible_text(term) # try: # element = WebDriverWait(driver, 10).until( # EC.presence_of_element_located((By.XPATH,'/html/body/div[3]/form/input[2]'))) # finally: # print('found') submit_button = driver.find_element_by_xpath('/html/body/div[3]/form/input[2]') submit_button.click() select = driver.find_element_by_xpath('//*[@id="subj_id"]') select.send_keys(Keys.CONTROL + Keys.ENTER) select = Select(driver.find_element_by_xpath('//*[@id="subj_id"]')) select.deselect_all() for subject in subjects: select.select_by_value(subject) submit = driver.find_element_by_xpath('/html/body/div[3]/form/span/input[1]') submit.click() # tbl = driver.find_element_by_xpath('/html/body/div[3]/form/div[2]/table').get_attribute('outerHTML') # df = pd.read_html(tbl) # print(df) # p = df.read_table table_id = driver.find_element(By.XPATH, '/html/body/div[3]/form/div[2]/table') rows = table_id.find_elements(By.TAG_NAME, "tr") # get all of the rows in the table full_message = '' courses_avail = {} for row in rows: # Get the columns (all the column 2) col = row.find_elements(By.TAG_NAME, "td") #note: index start from 0, 1 is col 2 for i in range(len(course_nums)): if course_nums[i] in row.text and subjects[i] in row.text: for colu in col: if col.index(colu) == 1: crn = colu.text for colu in col: if col.index(colu) == 12: seats_avail = colu.text full_message += subjects[i] + ' ' + course_nums[i] + ' has ' + seats_avail + ' available seats\n' if int(seats_avail) > 0: courses_avail[subjects[i] + ' ' +course_nums[i]] = crn print(courses_avail) print(full_message) # for row in rows: # # Get the columns (all the column 2) # col = row.find_elements(By.TAG_NAME, "td") #note: index start from 0, 1 is col 2 # for num in course_nums: # if num in row.text: # x = row.text.split() # print(x) # print(row.text) #prints text from the element # email = "*****@*****.**" # pas = "******" # sms_gateway = '*****@*****.**' # # The server we use to send emails in our case it will be gmail but every email provider has a different smtp # # and port is also provided by the email provider. # smtp = "smtp.gmail.com" # port = 587 # # This will start our email server # server = smtplib.SMTP(smtp,port) # # Starting the server # server.starttls() # # Now we need to login # server.login(email,pas) # # Now we use the MIME module to structure our message. # msg = MIMEMultipart() # msg['From'] = email # msg['To'] = sms_gateway # # Make sure you add a new line in the subject # msg['Subject'] = "----CLASS AVAILABILITY----\n\n" # # Make sure you also add new lines to your body # body = full_message # # and then attach that body furthermore you can also send html content. # msg.attach(MIMEText(body, 'plain')) # sms = msg.as_string() # server.sendmail(email,sms_gateway,sms) # # lastly quit the server # server.quit() # print("Took " + str(time.time() - start_time) + " seconds to run") return courses_avail