def testExpectedConditionElementLocatedSelectionStateToBe(self, driver, pages): if driver.capabilities['browserName'] == 'firefox' and driver.w3c: pytest.xfail("Marionette issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1297551") pages.load("formPage.html") element = driver.find_element_by_id('checky') WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) assert element.is_selected() is False with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) assert element.is_selected() is True
def testExpectedConditionElementLocatedSelectionStateToBe(self, driver, pages): pages.load("formPage.html") element = driver.find_element_by_id('checky') WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) assert element.is_selected() is False with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) assert element.is_selected() is True
def testExpectedConditionElementLocatedSelectionStateToBe(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) self.assertFalse(element.is_selected()) try: WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) self.fail("Expected TimeoutException to have been thrown") except TimeoutException as e: pass self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) self.assertTrue(element.is_selected())
def wait_for_selected(self, selector='', selected=True, **kwargs): ''' Wait for an element (checkbox/radio) to be selected. Parameters ---------- selector: str A CSS selector to search for. This can be any valid CSS selector. selected: bool Whether or not the element should be selected. Default True kwargs: Passed on to _wait_for ''' self._wait_for(EC.element_located_selection_state_to_be((By.CSS_SELECTOR, selector), selected), **kwargs)
def run(self, webdriver, params): """ Wait for things :param webdriver: :param params: :return: """ if isinstance(params, dict): if 'visibility_of' in params: """ Wait for the visibility of an element """ if 'element' in params['visibility_of']: element = params['visibility_of']['element'] else: raise DysonError("Key \"element\" is required") timeout = int(constants.DEFAULT_TIMEOUT) # seconds if 'timeout' in params['visibility_of']: timeout = int(params['visibility_of']['timeout']) return self._wait_for(element, expected_conditions.visibility_of_element_located, timeout, webdriver) if 'invisibility_of' in params: """ Wait for the invisibility of an element """ if 'element' in params['invisibility_of']: element = params['invisibility_of']['element'] else: raise DysonError("Key \"element\" is required") timeout = int(constants.DEFAULT_TIMEOUT) # seconds if 'timeout' in params['invisibility_of']: timeout = int(params['invisibility_of']['timeout']) return self._wait_for(element, expected_conditions.invisibility_of_element_located, timeout, webdriver) if 'presence_of' in params: """ Wait for the presence of an element """ if 'element' in params['presence_of']: element = params['presence_of']['element'] else: raise DysonError("Key \"element\" is required") timeout = int(constants.DEFAULT_TIMEOUT) # seconds if 'timeout' in params['presence_of']: timeout = int(params['presence_of']['timeout']) return self._wait_for(element, expected_conditions.presence_of_element_located, timeout, webdriver) if 'title_to_be' in params: """ Wait for the title to be something """ title = params['title_to_be'] timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['title_to_be']: timeout = int(params['title_to_be']['timeout']) return WebDriverWait(webdriver, timeout).until( expected_conditions.title_is(title) ) if 'title_to_contain' in params: """ Wait for the title to contain """ title = params['title_to_contain'] timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['title_to_contain']: timeout = int(params['title_to_contain']['timeout']) return WebDriverWait(webdriver, timeout).until( expected_conditions.title_contains(title) ) if 'alert' in params: """ Wait for an alert to be present """ timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['alert']: timeout = int(params['alert']['timeout']) return WebDriverWait(webdriver, timeout).until( expected_conditions.alert_is_present() ) if 'text_to_be_present' in params: """ Wait for text to be present in an element """ timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['text_to_be_present']: timeout = int(params['text_to_be_present']['timeout']) if 'in_element' in params['text_to_be_present']: in_element = params['text_to_be_present']['in_element'] if 'text' in params['text_to_be_present']: text = in_element['text'] strategy, selector = translate_selector_to_by(in_element) return WebDriverWait(webdriver, timeout).until( expected_conditions.text_to_be_present_in_element( (strategy, selector), text ) ) else: raise DysonError("Key \"text\" is required") else: raise DysonError("Key \"in_element\" is required") if 'clickable' in params: timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['clickable']: timeout = int(params['clickable']['timeout']) return self._wait_for(params['clickable']['element'], expected_conditions.element_to_be_clickable, timeout, webdriver) if 'value_to_be' in params: timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['value_to_be']: timeout = int(params['value_to_be']['timeout']) if 'in_element' in params['value_to_be']: in_element = params['value_to_be']['in_element'] if 'value' in params['value_to_be']: value = in_element['value'] strategy, selector = translate_selector_to_by(in_element) return WebDriverWait(webdriver, timeout).until( expected_conditions.text_to_be_present_in_element_value( (strategy, selector), value ) ) else: raise DysonError("Key \"text\" is required") else: raise DysonError("Key \"in_element\" is required") if 'staleness_of' in params: timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['staleness_of']: timeout = int(params['staleness_of']['timeout']) if 'element' in params['staleness_of']: element = params['staleness_of']['element'] return self._wait_for(element, expected_conditions.staleness_of, timeout, webdriver) else: raise DysonError("Key \"element\" is required") if 'presence_of_all' in params: timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['presence_of_all']: timeout = int(params['presence_of_all']['timeout']) if 'elements' in params['presence_of_all']: elements = params['presence_of_all'] return self._wait_for(elements, expected_conditions.presence_of_all_elements_located, timeout, webdriver) else: raise DysonError("Key \"elements\" is required") if 'element_to_be_selected' in params: timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['element_to_be_selected']: timeout = int(params['element_to_be_selected']['timeout']) if 'element' in params['element_to_be_selected']: element = params['element_to_be_selected']['element'] return self._wait_for(element, expected_conditions.element_located_to_be_selected, timeout, webdriver) else: raise DysonError("Key \"element\" is required") if 'selection_state_to_be' in params: timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['selection_state_to_be']: timeout = int(params['selection_state_to_be']['timeout']) if 'in_element' in params['selection_state_to_be']: in_element = params['selection_state_to_be']['in_element'] if 'state' in params['selection_state_to_be']: state = to_boolean(params['selection_state_to_be']['state']) strategy, selector = translate_selector_to_by(in_element) return WebDriverWait(webdriver, timeout).until( expected_conditions.element_located_selection_state_to_be( (strategy, selector), state ) ) else: raise DysonError("Key \"state\" is required") else: raise DysonError("Key \"in_element\" is required") if 'frame_and_switch' in params: timeout = int(constants.DEFAULT_TIMEOUT) if 'timeout' in params['frame_and_switch']: timeout = int(params['frame_and_switch']['timeout']) if 'frame' in params['frame_and_switch']: frame = params['frame_and_switch']['frame'] return self._wait_for(frame, expected_conditions.frame_to_be_available_and_switch_to_it, timeout, webdriver) else: raise DysonError("Key \"frame\" is required") else: self.fail("Invalid type. You must specify a valid action")
def testExpectedConditionElementLocatedSelectionStateToBe(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) self.assertFalse(element.is_selected()) try: WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass
def is_selected_be(self, locator, selected=True, timeout=10): '''判断元素的状态,selected是期望的参数true/False 返回布尔值''' result = WebDriverWait(self.driver, timeout, 1).until(EC.element_located_selection_state_to_be(locator, selected)) return result
def testExpectedConditionElementLocatedSelectionStateToBe(driver, pages): pages.load("formPage.html") element = driver.find_element_by_id('checky') WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) assert element.is_selected() is False with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) assert element.is_selected() is True
def testExpectedConditionElementLocatedSelectionStateToBe(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') WebDriverWait(self.driver, 0.7).until( EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) self.assertFalse(element.is_selected()) try: WebDriverWait(self.driver, 0.7).until( EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass
def is_selected_be(self, locator, is_selected=True): try: result = WebDriverWait(self.driver, 10, 1).until( EC.element_located_selection_state_to_be(locator, is_selected)) return result except: return False
def wait_until_element_located_selection_state_to_be(self, locator, is_selected, *args): by, value = self.format_locator(locator, *args) try: message = "Unable to get the element to be located selection state by {0}: '{1}' in the page '{2}'".format(by, value, self._driver.current_url) except WebDriverException: message = "Unable to get the element to be located selection state by {0}: '{1}'".format(by, value) return self.until(EC.element_located_selection_state_to_be((by, value), is_selected), message)
def is_selected_be(self, locator, selected=True, timeout=10): ''' 判断元素的状态,selected是期望的参数True/False ''' result = WebDriverWait(self.driver, timeout, 1).until( EC.element_located_selection_state_to_be(locator, selected)) return result
def element_located_selection_state_to_be(self, by, arg, is_selected, driver=None, timeout=30): ''' An expectation to locate an element and check if the selection state specified is in that state. locator is a tuple of (by, path) is_selected is a boolean @param: (by, arg) -- locator locator is tuple, as follow: (By.CLASS_NAME, class name) (By.CSS_SELECTOR, css selector) (By.ID, id) (By.LINK_TEXT, link text) (By.NAME, name) (By.PARTIAL_LINK_TEXT, partial link text) (By.TAG_NAME, tag name) (By.XPATH, xpath) ''' driver = driver or self.driver try: element = WebDriverWait(driver, timeout).until( EC.element_located_selection_state_to_be((by, arg), is_selected)) return element except Exception as e: # print("wait_for_element timeout: ") print(str(e)) return None
def element_located_selection_state_to_be(self, *, state, locator=None, **kwargs): """An expectation to locate an element and check if the selection state specified is in that state. This API supports kwargs style location-by shorthand. Eg: WaitUntil.element_located_selection_state_to_be((By.ID, 'loginForm'), ..) is the same as WaitUntil.element_located_selection_state_to_be(id = 'loginForm', ...) Arguments locator (tuple): location describing the location by state (bool): true or false timeout (int): seconds to wait for message (str): message to display if timed out kwargs (dict): any other argument for WebDriverWait() api """ locator, kwargs = utils.translate_args_with_passthru(locator, **kwargs) condition = EC.element_located_selection_state_to_be(locator, state) return self(condition, **kwargs)
def get_ad_contacts(self): """ Extract ad contacts """ # try to find contacts button try: contact_numbers_elem = self.driver.find_element_by_css_selector( 'div.contact-button') except NoSuchElementException: return list() # wait while button unclickable try: WebDriverWait(self.driver, 5).until( ec.element_to_be_clickable( (By.CSS_SELECTOR, 'div.contact-button'))) except NoSuchElementException: return list() self.click_btn(contact_numbers_elem) # wait while javasript will change information try: wait = WebDriverWait(self.driver, 30) wait.until( ec.element_located_selection_state_to_be( (By.CSS_SELECTOR, 'div.contact-button.activated'), False)) except TimeoutException: return list() contacts = contact_numbers_elem.find_element_by_tag_name( 'strong').text.split('\n') return contacts
def assert_is_selected_be(self, locator, selected=True, timeout=10): ''' 判断元素的状态,selected 是期望的参数 :param locator: 元素定位 :param selected: 被选中设置为True :param timeout: 超时时间 :return: 返回True或者False ''' WebDriverWait(self.driver, timeout, 1).until( EC.element_located_selection_state_to_be(locator, selected))
def is_selected_be(self,locator,selected=True,timeout=10): '''判断元素的状态,selected是期望参数true或者false返回布尔值''' if not isinstance(selected, bool): print("selected参数类型错误,必须传bool类型:selected=True") try: result = WebDriverWait(self.driver, timeout, 1).until( EC.element_located_selection_state_to_be(locator, selected)) return result except: return False
def wait_until_selected(self, seconds_to_wait=DEFAULT_TIMEOUT): """ Wait for an element to be selected, and raise the correct exception if it isn't """ try: WebDriverWait(self.driver, seconds_to_wait).until( ec.element_located_selection_state_to_be(self.locator, True)) except TimeoutException: if self.driver.find_element(*self.locator): raise InvalidElementStateException( f"Element '{self.locator}' exists but is not selected") return True
def testExpectedConditionElementLocatedSelectionStateToBe( self, driver, pages): if driver.capabilities['browserName'] == 'firefox' and driver.w3c: pytest.xfail( "Marionette issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1297551" ) pages.load("formPage.html") element = driver.find_element_by_id('checky') WebDriverWait(driver, 0.7).until( EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) assert element.is_selected() is False with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until( EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) driver.execute_script( "setTimeout(function(){document.getElementById('checky').checked = true}, 200)" ) WebDriverWait(driver, 0.7).until( EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) assert element.is_selected() is True
def get_isSelect_state(driver, way): wait = WebDriverWait(driver, 10) if "=>" in way: by = way[:way.find('=>')] value = way[way.find('=>') + 2:] if by == "" or value == "": # 语法错误,参考id=>element. raise NameError( "Grammatical errors, reference: 'id=>element'.") if by == 'id': element = wait.until( EC.element_located_selection_state_to_be(By.ID, value)) return element elif by == 'name': element = wait.until( EC.element_located_selection_state_to_be(By.NAME, value)) return element elif by == 'className': element = wait.until( EC.element_located_selection_state_to_be( By.CLASS_NAME, value)) return element elif by == 'css': element = wait.until( EC.element_located_selection_state_to_be( By.CSS_SELECTOR, value)) return element elif by == 'tagName': element = wait.until( EC.element_located_selection_state_to_be( By.TAG_NAME, value)) return element elif by == 'linkText': element = wait.until( EC.element_located_selection_state_to_be( By.LINK_TEXT, value)) return element else: element = wait.until( EC.element_located_selection_state_to_be(By.XPATH, value)) return element else: xpath = "//*[text()='{}']".format(way) element = wait.until( EC.element_located_selection_state_to_be(By.XPATH, xpath)) return element
def is_selected_be(self, locator, selected=True, timeout=10): """ 判断元素的选中状态是否符合预期,符合返回True,不符合返回False :param locator: :param timeout: :return: """ try: result = WebDriverWait(self.driver, timeout, 1).until( EC.element_located_selection_state_to_be(locator, selected)) except TimeoutException: print('元素%s的选中状态和预期的不符' % str(locator)) return False else: return result
def get_classroom(self, date, building): self.driver.get(self.base_url) logging.info('spider init successful') logging.info('start getting %s on %s' % (building, date)) # 设置时间 date_input = self.driver.find_element_by_id('datepicker') date_input.clear() date_input.send_keys(date) # 相当于从键盘输入 logging.info(' set date ok') # 当目标教室与当前教室相同时,checkBoxAll 不选中,否则选中 selected = self.driver.find_element_by_xpath('//select[@id="ddlBuild"]/option[@selected="selected"]') select_same = building == selected.get_attribute('value') checked = self.driver.find_element_by_id('checkBoxAll').is_selected() if (select_same and checked) or (not select_same and not checked): self.driver.find_element_by_id('checkBoxAll').click() # 换教学楼 select = Select(self.driver.find_element_by_id('ddlBuild')) select.select_by_value(building) logging.info(' change building ok') # 改变select后页面会刷新, 需要重新选择复选框checkBoxAll self.wait.until( EC.element_located_selection_state_to_be((By.ID, 'checkBoxAll'), False) ) self.driver.find_element_by_id('checkBoxAll').click() logging.info(' select all ok') self.wait.until( EC.text_to_be_present_in_element_value((By.ID, 'txtSelectedClass'), ';') ) # 删除以前的数据 if len(self.driver.find_elements_by_id('gvMain')) > 0: js = ''' var element = document.getElementById("%s"); element.parentNode.removeChild(element); ''' % 'gvMain' self.driver.execute_script(js) self.driver.find_element_by_id('btSearch').click() table = self.wait.until( EC.presence_of_element_located((By.ID, 'gvMain')) ) data = unicode(table.get_attribute('innerHTML')) logging.info('get classroom ok') return data.replace('<td> </td>', u'<td style="background-color:#00CC66;">自习</td>')
def create_departure_request(self): driver = self.driver self.utilities.login(self.driver, self.base_url, self.username, self.password) self.link_to_new_request('Salida de Activos Argos') self.fill_data_request() elementAmount = random.randrange(1, 30) #elementAmount = 1 for i in range(elementAmount): self.fill_element_data() WebDriverWait(driver, 10).until( EC.element_located_selection_state_to_be( (By.CSS_SELECTOR, 'table#myTable'), False)) sendRequestButton = driver.find_element( By.XPATH, '//button[text()="Enviar Solicitud"]') self.utilities.scrollToElement(driver, sendRequestButton) mouse = ActionChains(driver) mouse.move_to_element(sendRequestButton).click() mouse.perform() modalWindow = WebDriverWait(driver, 10).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#approveConfirmation-modal'))) acceptButton = WebDriverWait(modalWindow, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, 'a.btn-success'))) acceptButton.click() # Busca el consecutivo en el titulo titles = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.CSS_SELECTOR, 'blockquote'))).find_elements_by_css_selector("H4") consecutive = titles[0].find_element_by_css_selector('strong') consecutive = consecutive.get_attribute('innerHTML') self.requestData['requestId'] = consecutive.strip() print("Solicitud " + consecutive + " creada con " + str(len(self.requestData["elements"])) + " elementos") driver.quit() return self.requestData
def get_element_located_selection_state_to_be(self, locator, state=True, timeout=10): try: log.info("查看列表勾选结果和预期结果对比") result = WebDriverWait( self.driver, timeout=timeout, poll_frequency=1, ignored_exceptions=None).until( EC.element_located_selection_state_to_be(locator, state)) except Exception as msg: log.error("勾选结果和预期结果不匹配%s" % msg) return False else: log.info("确认符合预期") return result
def WebElement_Check_Radio(self, driver_object, element_obj, element_objname, element_objVal, element_objtype, element_input_arg): self.driver_object = driver_object self.element_obj = element_obj self.element_objname = element_objname self.element_objVal = element_objVal self.element_objtype = element_objtype self.element_input_arg = element_input_arg if (self.element_objtype == "Check_Box"): if (self.element_objname == "xpath"): self.click_ele = WebDriverWait(self.driver_object, 2).until( expected_conditions.element_located_selection_state_to_be( (By.XPATH, self.element_objVal))) if not (self.click_ele == self.element_input_arg): self.click_ele.click() elif (self.element_objname == "id"): self.click_ele = WebDriverWait(self.driver_object, 2).until( expected_conditions.element_located_selection_state_to_be( (By.ID, self.element_objVal))) if not (self.click_ele == self.element_input_arg): self.click_ele.click() elif (self.element_objname == "class_name"): self.click_ele = WebDriverWait(self.driver_object, 2).until( expected_conditions.element_located_selection_state_to_be( (By.CLASS_NAME, self.element_objVal))) if not (self.click_ele == self.element_input_arg): self.click_ele.click() if (self.element_objtype == "Radio_Button"): if (self.element_objname == "xpath"): self.click_ele = WebDriverWait(self.driver_object, 2).until( expected_conditions.element_located_selection_state_to_be( (By.XPATH, self.element_objVal))) if not (self.click_ele == self.element_input_arg): self.click_ele.click() elif (self.element_objname == "id"): self.click_ele = WebDriverWait(self.driver_object, 2).until( expected_conditions.element_located_selection_state_to_be( (By.ID, self.element_objVal))) if not (self.click_ele == self.element_input_arg): self.click_ele.click() elif (self.element_objname == "class_name"): self.click_ele = WebDriverWait(self.driver_object, 2).until( expected_conditions.element_located_selection_state_to_be( (By.CLASS_NAME, self.element_objVal))) if not (self.click_ele == self.element_input_arg): self.click_ele.click()
def create_element_ingress_request(self): driver = self.driver self.utilities.login(self.driver, self.base_url, self.username, self.password) self.link_to_new_request('Entrada de Elementos') self.fill_data_request() elementAmount = random.randrange(1, 30) #elementAmount = 1 for i in range(elementAmount): self.fill_element_data() WebDriverWait(driver, 10).until( EC.element_located_selection_state_to_be( (By.CSS_SELECTOR, 'table#myTable'), False)) sendRequestButton = driver.find_element_by_css_selector( "a#saveRequest-button") mouse = ActionChains(driver) mouse.move_to_element(sendRequestButton).click() mouse.perform() # Busca el consecutivo en el titulo titles = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.CSS_SELECTOR, 'blockquote'))).find_elements_by_css_selector("H4") consecutive = titles[0].find_element_by_css_selector('strong') consecutive = consecutive.get_attribute('innerHTML') self.requestData['requestId'] = consecutive # Hace las comparaciones respectivas de la solicitud creada self.assert_request() print("Solicitud " + str(consecutive) + " Creada con " + str(len(self.requestData['elements'])) + " elementos") driver.quit() return self.requestData
def wait_until (self, by, path, *args): """Wait until expected condition is met. Used internal to find method""" try: wait = WebDriverWait(self.driver, 10) if self.config["until"] == "click": _ = wait.until(EC.element_to_be_clickable((by, path))) if self.config["until"] == "present": _ = wait.until(EC.presence_of_element_located((by, path))) if self.config["until"] == "visible": _ = wait.until(EC.visibility_of_element_located((by, path))) if self.config["until"] == "invisible": _ = wait.until(EC.invisibility_of_element_located((by, path))) if self.config["until"] == "text_present": _ = wait.until(EC.text_to_be_present_in_element((by, path, kwargs))) #_text if self.config["until"] == "text_present_locator": _ = wait.until(EC.text_to_be_present_in_element_value((by, path, kwargs))) #_text if self.config["until"] == "selection_state": _ = wait.until(EC.element_selection_state_to_be((by, path))) if self.config["until"] == "located_selection_state": _ = wait.until(EC.element_located_selection_state_to_be((by, path, kwargs))) #is_selected return True except: return False
def create_consumables_ingress_request(self): driver = self.driver self.utilities.login(self.driver, self.base_url, self.username, self.password) self.link_to_new_request('Entrada de Consumibles') self.fill_data_consumables_request() consumablesAmount = random.randrange(1, 10) #consumablesAmount = 1 for i in range(consumablesAmount): self.fill_consumables_data() WebDriverWait(driver, 10).until( EC.element_located_selection_state_to_be( (By.CSS_SELECTOR, 'table#myTable'), False)) # Envía la solicitud sendRequestButton = driver.find_element_by_link_text( "Enviar Solicitud") mouse = ActionChains(driver) mouse.move_to_element(sendRequestButton).click() mouse.perform() # Busca el consecutivo en el titulo titles = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.CSS_SELECTOR, 'blockquote'))).find_elements_by_css_selector("H4") consecutive = titles[0].find_element_by_css_selector('strong') consecutive = consecutive.get_attribute('innerHTML').strip() self.requestData['requestId'] = consecutive driver.quit() return self.requestData
element = WebDriverWait(driver, 10).until(EC.title_is((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.title_contains((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until(EC.visibility_of( (By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.text_to_be_present_in_element((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.text_to_be_present_in_element_value((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.frame_to_be_available_and_switch_to_it((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.invisibility_of_element_located((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.element_to_be_selected((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.element_located_to_be_selected((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.element_selection_state_to_be((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.element_located_selection_state_to_be((By.ID, "myDynamicElement"))) element = WebDriverWait(driver, 10).until( EC.alert_is_present((By.ID, "myDynamicElement")))
def element_located_selection_state_to_be(self,selector): '''判断某个元素的选中状态是否符合预期''' # self.driver.find_element_by_xpath(".//*[@id='gxszButton']/a[1]").click() locator = self.handle_locator(selector) return WebDriverWait(self.driver, 10).until( EC.element_located_selection_state_to_be(locator, True))
self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(self.driver, 0.7).until(EC.element_selection_state_to_be(element, True)) self.assertTrue(element.is_selected()) def testExpectedConditionElementLocatedSelectionStateToBe(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), False)) self.assertFalse(element.is_selected()) try: WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True)) self.assertTrue(element.is_selected()) def testExpectedConditionAlertIsPresent(self): self._loadPage('blank') try: WebDriverWait(self.driver, 0.7).until(EC.alert_is_present()) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass self.driver.execute_script("setTimeout(function(){alert('alerty')}, 200)") WebDriverWait(self.driver, 0.7).until(EC.alert_is_present()) alert = self.driver.switch_to_alert() self.assertEqual('alerty', alert.text) alert.dismiss()
'''判断某个元素中是否可见并且是enable的,代表可点击''' driver.find_element_by_xpath("//*[@id='wrapper']/div[6]/a[1]").click() #WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//*[@id='wrapper']/div[6]/a[1]"))).click() #WebDriverWait(driver,10).until(EC.staleness_of(driver.find_element(By.ID,'su'))) '''等待某个元素从dom树中移除''' #这里没有找到合适的例子 WebDriverWait(driver, 10).until( EC.element_to_be_selected( driver.find_element(By.XPATH, "//*[@id='nr']/option[1]"))) '''判断某个元素是否被选中了,一般用在下拉列表''' WebDriverWait(driver, 10).until( EC.element_selection_state_to_be( driver.find_element(By.XPATH, "//*[@id='nr']/option[1]"), True)) '''判断某个元素的选中状态是否符合预期''' WebDriverWait(driver, 10).until( EC.element_located_selection_state_to_be( (By.XPATH, "//*[@id='nr']/option[1]"), True)) '''判断某个元素的选中状态是否符合预期''' driver.find_element_by_xpath(".//*[@id='gxszButton']/a[1]").click() instance = WebDriverWait(driver, 10).until(EC.alert_is_present()) '''判断页面上是否存在alert,如果有就切换`到alert并返回alert的内容''' print(instance.text) instance.accept() driver.close()
#coding=utf-8 from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 判断下拉框的选项是否可选,可选则返回True,否则返回False # 调用时,首先要先选中下拉框的某个选项,再调用此函数 # tuple1为一个元组,里面包含了两个值,一个是查找方式,通常是By.ID,一个是需要判断的下拉选项的id # 元组中如果第一个元素是By.NAME,那么第二个元素则为需要怕暖的下拉选项的name # True代表可用,driver为浏览器的实例对象,ws代表等待的秒数,es代表在ws时间段内每隔多少毫秒尝试选择一次 # 例:isselected((By.ID, "orange"),True,10,0.2) # 代表某下拉选项的id为orange,在10秒内,每隔0.2秒(200毫秒)尝试选择一次,直到选择成功,成功后代码向后执行 def isselected(tuple1,True,driver,ws,es): wait = WebDriverWait(driver,ws,es) return wait.until(EC.element_located_selection_state_to_be(tuple1,True)) # 判断页面上某元素是否可见和可被点击(任何元素都可以被点击,不仅限于输入框),可被点击返回该元素对象,否则返回False # driver为浏览器实例化对象,ws为等待的秒数,es为ws时间段内每隔多少毫秒查看一次该元素是否可见和可被点击 # vcxpath为查找该元素所使用的xpath语句 # 例:visible_clicked(driver,10,0.2,"//input[@id='kw']") def visible_clicked(driver,ws,es,vcxpath): wait = WebDriverWait(driver,ws,es) return wait.until(EC.element_to_be_clickable((By.XPATH,vcxpath))) # 判断frame是否可用,如可用,则返回True并切入frame,不可用则返回False # driver为浏览器的实例化对象,ws为等待的秒数,es为ws时间段内每隔多少毫秒判断一次frame是否可用 # tuple有两个值,一个是查找方式,可以By.ID,也可以 By.XPATH,另一个是该frame的id # tuple的第一个值如果是By.NAME,那么第二个值就是该frame的NAME # 例1:frame_isusabled(driver,10,0.2,(By.ID, "x-URS-iframe"))
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait import selenium.webdriver.support.expected_conditions as EC driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(30) driver.get("https://demo.actitime.com/login.do") wait = WebDriverWait(driver,30) status = wait.until(EC.element_located_selection_state_to_be((By.ID,'keepLoggedInCheckBox'),False)) if status==True: print(status,"Check box is not selected") else: print(status,"Check box is selected") driver.close()
def is_selected_be(self, element, selected=True, timeout=10): '''expected status of selected is True or False, return boolean''' result = WebDriverWait(self.driver, timeout, 1).until(EC.element_located_selection_state_to_be(element, selected)) return result
driver.get(url) element = driver.find_element_by_xpath("//*[@class='nav']/li[2]") #构造对象 action_chains = AC(driver) action_chains.move_to_element(element).perform() action_chains.reset_actions() sleep(3) driver.find_element_by_link_text("单程").click() sleep(3) radio = driver.find_element_by_id('sf2') radio.click() locators = (By.XPATH, "//input[@id='sf2']") try: #显性等待,判断radio是否被勾选 WebDriverWait(driver, 5).until( EC.element_located_selection_state_to_be(locators, True)) #判断勾选checkbox checkbox = driver.find_element_by_xpath("//input[@id='auto_query']") checkbox.click() # 显性等待,判断checkbox是否被勾选 WebDriverWait(driver, 5).until(EC.element_selection_state_to_be(checkbox, True)) # 出发地 fs = driver.find_element_by_xpath("//input[@id='fromStationText']") fs.clear() fs.send_keys('深圳') sleep(2) # 目的地 ts = driver.find_element_by_xpath("//input[@id='toStationText']") ts.clear() ts.send_keys('武汉')