def comapre_cluster(self): self.driver.find_element_by_css_selector('p >span').click() time.sleep(5) select_district = WebDriverWait(self.driver, 30).until( EC.element_located_to_be_selected((By.ID, 'choose_dist'))) select_block = WebDriverWait(self.driver, 30).until( EC.element_located_to_be_selected((By.ID, 'choose_block'))) select_cluster = WebDriverWait(self.driver, 30).until( EC.element_located_to_be_selected((By.ID, 'choose_cluster'))) select_district = Select(select_district) select_block = Select(select_block) select_cluster = Select(select_cluster) count = 0 for x in range(1, len(select_district.options)): select_district.select_by_index(x) for y in range( len(select_block.options) - 1, len(select_block.options)): select_block.select_by_index(y) for z in range(1, len(select_cluster.options)): select_cluster.select_by_index(z) list = self.driver.find_elements_by_class_name(Data.dots) elem = self.driver.find_element_by_id( Data.schoolcount).text res = re.sub("\D", "", elem) if int(len(list) - 1) != int(res): count = count + 1 print( "no of schools and number of dots are mis matched at" + " " + select_district.first_selected_option.text + " " + select_block.first_selected_option.text + " " + select_cluster.first_selected_option.text) return count
def testExpectedConditionElementLocatedToBeSelected(driver, pages): pages.load("formPage.html") element = driver.find_element_by_id('checky') with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) assert element.is_selected() is True
def testExpectedConditionElementLocatedToBeSelected(self, driver, pages): pages.load("formPage.html") element = driver.find_element_by_id('checky') with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) assert element.is_selected() is True
def testExpectedConditionElementLocatedToBeSelected(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') with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) assert element.is_selected() is True
def isElementSelected(xpath: str, driver) -> bool: try: return WebDriverWait(driver, 1).until( EC.element_located_to_be_selected((By.XPATH, xpath))) except: try: return WebDriverWait(driver, 1).until( EC.element_located_to_be_selected((By.XPATH, xpath))) except: return False
def testExpectedConditionElementLocatedToBeSelected(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') try: WebDriverWait(self.driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) 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_to_be_selected((By.ID, 'checky'))) self.assertTrue(element.is_selected())
def select_element_check(self, type, value, timeout=1): try: if type == "xpath": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected((By.XPATH, value))) elif type == "id": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected((By.ID, value))) elif type == "name": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected((By.NAME, value))) elif type == "tagname": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected((By.TAG_NAME, value))) elif type == "classname": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected((By.CLASS_NAME, value))) elif type == "css": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected( (By.CSS_SELECTOR, value))) elif type == "link": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected((By.LINK_TEXT, value))) elif type == "plt": return WebDriverWait(self.driver, timeout).until( EC.element_located_to_be_selected( (By.PARTIAL_LINK_TEXT, value))) except Exception: return False
def is_element_selected(self, located: str, element=None, mode=True): """ *不佳的封装 判断元素是否可以被选中 user: is_element_selected('css=>#c_ph_login') 方式一 is_element_selected('',with上文的元素对象,mode=False) 方式二 located ='' 反正走不到上面分支 :param located: 定位到的元素 :return:boolean """ if mode: return WebDriverWait(self.driver, 10).until(EC.element_located_to_be_selected(self.find_element_wait(located))) else: return WebDriverWait(self.driver, 10).until( EC.element_located_to_be_selected(element))
def element_located_to_be_selected(self, by, arg, driver=None, timeout=30): ''' An expectation for the element to be located is selected. locator is a tuple of (by, path) @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_to_be_selected((by, arg))) return element except Exception as e: # print("wait_for_element timeout: ") print(str(e)) return None
def is_selected(self, locator): try: result = WebDriverWait(self.driver, 10, 1).until( EC.element_located_to_be_selected(locator)) return result except: return False
def element_should_not_be_selected(self, locator, ele, timeouts=6): """ 验证元素是未被选中的 :param locator: 'xpath' :param ele: '//*[@id="app"]/div/div/form/div[2]/div/div[1]/input' :param timeouts: 1 :return: '{"result": "INFO", "msg": "元素 //*[@id="app"]/div/div/form/div[2]/div/div[1]/input 被选中", "flag": "True"}' """ try: WebDriverWait(self.driver, timeouts).until( EC.element_located_to_be_selected( (self.locator_dict[locator], ele))) is_selected = self.driver.find_element(self.locator_dict[locator], ele).is_selected() if is_selected is False: msg = '元素 %s 未被选中' % ele.replace("\"", "'") flag = 'True' else: msg = '元素 %s 被选中' % ele.replace("\"", "'") flag = 'False' result = '{"result": "INFO", "msg": "%s", "flag": "%s"}' % (msg, flag) except: msg = '元素 %s 不可选' % ele.replace("\"", "'") self.logger.error(msg) result = '{"result": "ERROR", "msg": "%s"}' % msg raise AssertionError(result) return result
def wait_for_element(c, element_selector): try: element = WebDriverWait(c, 3, poll_frequency=0.4).until( EC.element_located_to_be_selected( (By.CSS_SELECTOR, element_selector))) finally: return
def get_element_status(self, loc): try: result = WebDriverWait(self.driver).until( EC.element_located_to_be_selected(loc)) return result except ElementNotSelectableException: print(u"%s page can not find %s element" % (self, loc))
def tap_discover_tab(self, timeout=10): """ Summary: 点击发现tab Args: timeout: 等待时长 """ log.logger.info("等待相机气泡消失再点击相机按钮") while self.wait_for_element_present( self.base_parent, timeout=5, id='com.jiuyan.infashion:id/id_fl_parster'): log.logger.info("相机气泡存在,继续等待5秒") time.sleep(5) log.logger.info("开始点击发现tab") self.discovery_tab.tap() log.logger.info("发现tab点击完毕") try: WebDriverWait(self.base_parent, timeout).until( EC.element_located_to_be_selected( (MobileBy.ACCESSIBILITY_ID, '热门话题'))) log.logger.info("成功进入发现tab页面") return True except exceptions.TimeoutException: log.logger.error("进入发现tab页面失败") return False
def test_papa003_charts_hidden_when_unselected(dash_duo, run_paralympics_app): """ GIVEN the Dashboard page has loaded WHEN both the Winter and Summer options in the checklist with the id 'mf-ratio-checklist' are unselected THEN the divs with the ids of 'stacked-bar-gender-win' and 'stacked-bar-gender-sum' should have a `style="display: none"' attribute """ dash_duo.wait_for_element("#mf-ratio-checklist", timeout=4) WebDriverWait(dash_duo.driver, 3).until( EC.element_located_to_be_selected( (By.CSS_SELECTOR, "#mf-ratio-checklist > " "label:nth-child(1) > " "input:nth-child(1)"))) checkboxes = dash_duo.find_elements("#mf-ratio-checklist input") for c in checkboxes: # selenium click() method failed, used guidance here # https://stackoverflow.com/questions/46253566/selenium-cant-click-specific-checkbox and converted from Java # to Python as below dash_duo.driver.execute_script("arguments[0].click();", c) display_attribute_w = dash_duo.find_element( "#stacked-bar-gender-win").value_of_css_property('display') display_attribute_s = dash_duo.find_element( "#stacked-bar-gender-sum").value_of_css_property('display') assert display_attribute_w == 'none' assert display_attribute_s == 'none'
def is_selected(self, locator): ''' 判断元素是否选中,一般用于下拉列表''' try: result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.element_located_to_be_selected(locator)) return result except: return False
def select_group(self, group_name='friends'): """ Args: group_name: 两个值friend表示勾选朋友,interest表示勾选订阅 Returns: """ words = {'friends': '朋友', 'interest': '订阅'} if group_name in ('friends', 'interest'): log.logger.info("开始点击\"{}\"分组".format(words[group_name])) getattr(self, group_name + '_check', None).tap() log.logger.info("点击完毕") log.logger.info("检查是否已选中\"{}\"分组".format(words[group_name])) try: WebDriverWait(self.base_parent, 3).until( EC.element_located_to_be_selected( (MobileBy.ID, 'com.jiuyan.infashion:id/uc_remark_sort_{}'.format( group_name)))) log.logger.info("已选中\"{}\"分组".format(words[group_name])) return True except: log.logger.error("选择\"{}\"分组失败".format(words[group_name])) return False else: log.logger.error("group_name值错误,只能选择friends或者interest") return False
def is_selected(self, locator, timeout=10): '''判断元素被选中''' result = WebDriverWait(self.driver, timeout, 1).until( EC.element_located_to_be_selected(locator)) return result
def tap_zan(self): """ Summary: 点赞 Returns: """ log.logger.info("开始点赞") self.zan_button.tap() log.logger.info("点赞完毕") try: # 点赞按钮被选中 WebDriverWait(self.base_parent, 10).until( EC.element_located_to_be_selected(( MobileBy.ID, 'com.jiuyan.infashion:id/friend_card_item_user_op_content_fav' ))) if self.wait_for_element_present( id='com.jiuyan.infashion:id/layout_like_users'): log.logger.info("存在点赞人群头像组") return True log.logger.error("不存在点赞人群头像组") return False except TimeoutException: log.logger.error("点赞按钮没选中") return False
def testExpectedConditionElementLocatedToBeSelected(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') with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until( EC.element_located_to_be_selected((By.ID, 'checky'))) driver.execute_script( "setTimeout(function(){document.getElementById('checky').checked = true}, 200)" ) WebDriverWait(driver, 0.7).until( EC.element_located_to_be_selected((By.ID, 'checky'))) assert element.is_selected() is True
def open_url(self) -> None: """ function opens a browser and looking for result for user request and opening first met link :return: function return none """ self.driver.get('https://www.youtube.com/') try: WebDriverWait(self.driver, 5).until( EC.element_to_be_clickable(( By.XPATH, '/html/body/ytd-app/ytd-popup-container/paper-dialog/' 'yt-upsell-dialog-renderer/div/div[3]/div[1]/yt-button-renderer/a/' 'paper-button/yt-formatted-string'))).click() WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#introAgreeButton>div.Vwe4Vb.MbhUzd'))).click() except: print(f'no alerts') search = self.driver.find_element_by_name("search_query") search.clear() search.send_keys(self.search_word) submit_button = self.driver.find_element_by_id("search-icon-legacy") submit_button.click() WebDriverWait(self.driver, 10).until( EC.element_located_to_be_selected( (By.XPATH, '//*[@id="mouseover-overlay"]'))).click()
def element_is_select(self,selector): ''' 判断元素是否被选中 :param selector: :return: ''' return EC.element_located_to_be_selected(selector)(self.driver)
def is_selected(browser,locator): try: WebDriverWait(browser, 2, 0.5).until(EC.element_located_to_be_selected(locator)) return True except EC.WebDriverException as e: log.info('%s元素没有被选择'%locator[1]) return False
def find_ele(self, method="XPATH", pat="", pat_params="", type="located", wait_time=10): '''查找页面元素''' try: self.params = pat if pat_params != "": pat = pat % pat_params self.params = pat if type == "located": self.ele = WebDriverWait(self.driver, wait_time).until( EC.presence_of_element_located((getattr(By, method), pat))) elif type == "clickable": self.ele = WebDriverWait(self.driver, wait_time).until( EC.element_to_be_clickable((getattr(By, method), pat))) elif type == "selected": self.ele = WebDriverWait(self.driver, wait_time).until( EC.element_located_to_be_selected((getattr(By, method), pat))) except Exception as e: logger.error(f"查找页面元素{self.params}失败", exc_info=True) self.ele = "" raise e finally: return self.ele
def explicit_wait_method(self, condition, address, extra=None): wait = WebDriverWait(driver, 20) element = None locater = By.XPATH, address if condition == "presenceofelement": cc = ec.presence_of_element_located(locater) element = wait.until(cc) elif condition == "elementtobeselected": cc = ec.element_to_be_selected(locater) element = wait.until(cc) elif condition == "elementlocatedtobeselected": cc = ec.element_located_to_be_selected(locater) element = wait.until(cc) elif condition == "elementtobeclickable": cc = ec.element_to_be_clickable(locater) wait.until(cc) elif condition == "visibilityofelementlocated": cc = ec.visibility_of_element_located(locater) wait.until(cc) elif condition == "titlecontains": cc = ec.title_contains(extra) element = wait.until(cc) elif condition == "presenceofallelementslocated": cc = ec.presence_of_all_elements_located(locater) element = wait.until(cc) elif condition == "visibilityof": cc = ec.visibility_of(element) element = wait.until(cc) else: log.error("invalid condition type for wait") return element
def is_selected_located(self, located: str): """ 判断元素是否可以被选中,直接嵌套元素对象 :param located:元组=>字符串对象 :return:boolean """ return WebDriverWait(self.driver, 10).until( EC.element_located_to_be_selected(self.find_element_wait(located)))
def is_element_available(self, how, what, timeout=10): try: WebDriverWait(self.browser, timeout).until( EC.element_located_to_be_selected((how, what))) except TimeoutException: return True return False
def testExpectedConditionElementLocatedToBeSelected(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') try: WebDriverWait(self.driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass
def is_selected_element(self, element:str): """ 判断元素是否可以被选中 嵌套上文元素对象 :param element:with上文的元素对象 :return:booleanboolean """ return WebDriverWait(self.driver, 10).until( EC.element_located_to_be_selected(element))
def wait_for_check_status(self, locator: "Locator", checked: bool = True, timeout: int = _DEFAULT_TIMEOUT) -> None: """ Espera que un elemento esté tildado (checkeado) Args: locator (Locator): objeto que abstrae el elemento a esperar checked (bool): valor esperado del check timeout (int): cantidad máxima de tiempo a esperar antes de lanzar una excepción Returns: None """ wait = self.get_wait(timeout) if checked: wait.until(ec.element_located_to_be_selected(locator.ret_locator)) else: wait.until_not(ec.element_located_to_be_selected(locator.ret_locator))
def get_wait_condition(self, bylocator, condition): if condition is WaitCondition.ELEMENTVISIBLE: return expected_conditions.visibility_of_element_located(bylocator) elif condition is WaitCondition.ELEMENTPRESENT: return expected_conditions.presence_of_element_located(bylocator) elif condition is WaitCondition.ELEMENTSELECTABLE: return expected_conditions.element_located_to_be_selected( bylocator)
def is_selected(self,loc, timeout=10): ''' 判断元素被选中,返回布尔值 :param loc: :param timeout: :return: ''' result = WebDriverWait(self.driver, timeout, 1).until(EC.element_located_to_be_selected(loc)) return result
def assert_is_selected(self, locator, timeout=10): ''' 判断元素是否被选中 :param locator:元素定位 :param timeout: 超时时间 :return: 返回True或者False ''' WebDriverWait(self.driver, timeout, 1).until(EC.element_located_to_be_selected(locator))
def wait_element_selected(driver, locator, by=By.XPATH, timeout=30): """ :param driver: :param locator: :param by: :param timeout: :return: """ try: if ui.WebDriverWait(driver, timeout).until(ec.element_located_to_be_selected((by, locator))): return driver.find_element(by, locator) except TimeoutException: return False
def is_selected(self, locator, timeout=10): '''判断元素被选中,返回布尔值,''' result = WebDriverWait(self.driver, timeout, 1).until(EC.element_located_to_be_selected(locator)) return result
def is_element_selected(locator, timeOut=0): ''' Check whether the element to be located is selected ''' try: return _wait(timeOut).until(EC.element_located_to_be_selected(Element(locator)._get())) except WebDriverException: return False
def get_checkbox_status(self,xpath): ''' 获取checkbox的状态 ''' status = WebDriverWait(self.conf.driver, TIME_OUT).until(EC.element_located_to_be_selected((By.XPATH,xpath))) return status
except TimeoutException, e: pass self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(self.driver, 0.7).until(EC.element_to_be_selected(element)) self.assertTrue(element.is_selected()) def testExpectedConditionElementLocatedToBeSelected(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') try: WebDriverWait(self.driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky'))) 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_to_be_selected((By.ID, 'checky'))) self.assertTrue(element.is_selected()) def testExpectedConditionElementSelectionStateToBe(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') WebDriverWait(self.driver, 0.7).until(EC.element_selection_state_to_be(element, False)) self.assertFalse(element.is_selected()) try: WebDriverWait(self.driver, 0.7).until(EC.element_selection_state_to_be(element, 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_selection_state_to_be(element, True)) self.assertTrue(element.is_selected())