def research_route(self): depart_xpath = "//select[@id='depart_sel_apt']/option[@value='{}']".format( self.departure) arrive_xpath = "//select[@id='arrive_sel_apt']/option[@value='{}']".format( self.arrival) try: depart_element = self.driver.find_element_by_xpath(depart_xpath) arrive_element = self.driver.find_element_by_xpath(arrive_xpath) WebDriverWait(self.driver, 10).until(EC.element_to_be_selected( (depart_element))) WebDriverWait(self.driver, 10).until(EC.element_to_be_selected( (arrive_element))) except TimeoutException: print("Time exceeded!") xpath = "//input[@name='submit']" submit_btn = self.driver.find_element_by_xpath(xpath) submit_btn.click() xpath = "//td[text()='Route Details']" message = "Route details loaded" self.wait_until_loaded(xpath, message)
def explicit_wait_methods(): # Variables and objects url = "https://chercher.tech/practice/explicit-wait-sample-selenium-webdriver" # click button: #populate-text # explictitly wait until # text_to_be_present_in_element(locator,text_) -- "Selenium" # locators: h2 (id), //h2[@id='h2'] (xpath), #h2 (css selector) # driver.find_element_by_xpath("//h2[@id='h2' and text()='Selenium Webdriver']") -- this is not good msg_xpath = "//h2[@id='h2']" msg_id = "h2" msg_css_selector = "#h2" # locator1 = (By.XPATH, msg_xpath) extd_txt = "Selenium Webdriver" wdwait = WebDriverWait(driver, 60) # Steps starts here driver.get(url) print("## Case 1: text_to_be_present_in_element") element = driver.find_element_by_id("populate-text") # finding the button to click # printing the message of the h2 before clicking msg_txt = driver.find_element_by_xpath(msg_xpath) print(f"Current message text: {msg_txt.text}") element.click() print("waiting until expected text to appear ...") # WebDriverWait(driver, 60).until(expected_conditions.text_to_be_present_in_element((By.XPATH, msg_xpath), extd_txt)) msg = wdwait.until(EC.text_to_be_present_in_element((By.XPATH, msg_xpath), extd_txt)) print(f"did message appear now? - {msg}") print(f"New (expected) message text: {msg_txt.text}") print("## Case 2: visibility_of_element_located") display_btn_id = "display-other-button" driver.find_element_by_id(display_btn_id).click() print("waiting until enabled button appears...") enabled_btn = wdwait.until(EC.visibility_of_element_located((By.ID, 'hidden'))) enabled_btn.click() print("waiting until enabled button disappears...") wdwait.until_not(EC.visibility_of_element_located((By.ID, 'hidden'))) print("case 2 completed!") print("## Case 3: element_to_be_clickable") enabled_btn_id = "enable-button" driver.find_element_by_id(enabled_btn_id).click() print("waiting until Button button is clickable...") wdwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#disable'))) print("case 3 completed!") print("## Case 4: element_to_be_selected") check_btn_id = "checkbox" wdwait.until(EC.element_to_be_clickable((By.ID, check_btn_id))).click() driver.find_element_by_id(check_btn_id).click() print("waiting until box is selected...") wdwait.until(EC.element_to_be_selected((By.CSS_SELECTOR, '#ch'))) # this return True/False driver.find_element_by_css_selector("#ch").click() print("waiting until box is unchecked...") wdwait.until_not(EC.element_to_be_selected((By.CSS_SELECTOR, '#ch'))) print("case 4 completed!")
def testExpectedConditionElementToBeSelected(driver, pages): pages.load("formPage.html") element = driver.find_element_by_id('checky') with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.element_to_be_selected(element)) driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)") WebDriverWait(driver, 0.7).until(EC.element_to_be_selected(element)) assert element.is_selected() is True
def elementToBeSelected(self, locationType, locatorExpression): "期望某个元素的被选中,函数本身参数为一个WebDriver实例对象,这里统一传入定位方式和定位表达式,返回布尔值" if locationType == "xpath": return EC.element_to_be_selected( self.driver.find_element_by_xpath(locatorExpression))( self.driver) elif locationType == "id": return EC.element_to_be_selected( self.driver.find_element_by_id(locatorExpression))(self.driver) else: return "未找到定位方式,请确认定位方法是否准确"
def testExpectedConditionElementToBeSelected(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') try: WebDriverWait(self.driver, 0.7).until(EC.element_to_be_selected(element)) 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_to_be_selected(element)) self.assertTrue(element.is_selected())
def testExpectedConditionElementToBeSelected(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_to_be_selected(element)) driver.execute_script( "setTimeout(function(){document.getElementById('checky').checked = true}, 200)" ) WebDriverWait(driver, 0.7).until(EC.element_to_be_selected(element)) assert element.is_selected() is True
def wait_for_element(self, condition, timeout=25, pollFrequency=0.5): try: wait = WebDriverWait(Config.driver, timeout=timeout, poll_frequency=pollFrequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) condition = condition.lower() # click = element_to_be_clickable # present = presence_of_element_located # select = element_to_be_selected if condition == 'click': wait.until( EC.element_to_be_clickable( (self.locator_type, self.locator))) elif condition == 'present': wait.until( EC.presence_of_element_located( (self.locator_type, self.locator))) elif condition == 'select': wait.until( EC.element_to_be_selected( (self.locator_type, self.locator))) except: self.log.warn("Element hasn't appeared on the web page")
def element_to_be_selected(locatortype, locator): try: wait = WebDriverWait(BaseFixture.driver, 10) element = BaseFixture.get_webelement(locatortype, locator) wait.until(EC.element_to_be_selected(element)) except: print(traceback.print_exc())
def wait_until_element_present(self, locator_value, action_type, locator_type='xpath', driver_timeout=10, poll_frequency=1): try: locator_type = self.updated_locator_type(locator_type) wait = WebDriverWait(self.driver, driver_timeout, poll_frequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) if action_type == 'click': element = wait.until( expected_conditions.element_to_be_clickable( (By.XPATH, "//input[@id='benzradio']"))) return element elif action_type == 'select': element = wait.until( expected_conditions.element_to_be_selected( locator_type, locator_value)) return element else: print('action type not matched with the available options') except: print("No such element found") return False
def is_selected(self, locator): """判断元素被选中,返回布尔值, 一般用在下拉框""" try: return self.according_wait(EC.element_to_be_selected(locator)) except TimeoutException: self.log.error('元素没有定位到:%s' % str(locator)) return False
def test_explictWait(self): url = r"C:\Users\Mr雷的电脑\Desktop\selenium_python\test_html\explicit_wait.html" self.driver.get(url) try: wait = WebDriverWait(self.driver, 10, 0.2) wait.until(EC.title_is(u"你喜欢的饶舌歌手")) print("网页标题是:你喜欢的水果") element = WebDriverWait( self.driver, 10).until(lambda x: x.find_element_by_xpath( "//input[@value = 'Display alert box']")) element.click() alert = wait.until(EC.alert_is_present()) print(alert.text) alert.accept() kanye = self.driver.find_element_by_id('kanye') kanyeElement = wait.until(EC.element_to_be_selected(kanye)) print(u"kanye处于选择状态") wait.until(EC.element_to_be_clickable((By.Id, 'check'))) print(u"复选框可见并且能被点击") except TimeoutException: print(traceback.print_exc()) except NoSuchElementException: print(traceback.print_exc()) except Exception: print(traceback.print_exc())
def is_element_selected(self, how, what, timeout=2): try: WebDriverWait(self.browser, timeout).until(EC.element_to_be_selected((how, what))) except TimeoutException: return False return True
def gettext(web, path_iframe="//*[@id='doc_preview']/div/iframe", check_class="textLayer--absolute"): #建立一个空的list存文本 textlist = [] #加载进入文本框 web.switch_to.frame(web.find_element_by_xpath(path_iframe)) #等待文本加载,使用内置方法检查,以textLayer--absolute为检查点,检查是否加载完成 #两秒后开始检查 wait = WebDriverWait(web, 2) #每500毫秒轮检一次,其实还不如sleep效率高,但是稳的一批,谁知道网络会出什么鬼 wait.until( expected_conditions.element_to_be_selected( (By.CLASS_NAME, check_class))) #加载过滤模块,注意,要配置lxml环境,或者使用python内置方法,不过忘记python内置方法是什么了.... text = BeautifulSoup(web.page_source, 'lxml') #定位文本位置,读取全部含文本元素,这个地方之前要补一个检测未提交的方法,然后用try函数加强 allcontent = text.find_all(class_=check_class) #通过循环,依次抽取含文本元素 for eachsentence in allcontent: #将元素中的文本取出 #去除空格 sentence = eachsentence.getText().strip() #加入列表中保证 textlist.append(sentence) return textlist
def __wait_conditions(self, wait_condition: str, locator, text=None): """ Основной метод для определения необходимого типа ожидания элемента :param wait_condition: тип ожидания элемента :param locator: локатор элемента :param text: ожидаемый текст :return: condition - состояние waiter :rtype: object """ presence_of_element_located = lambda: ec.presence_of_element_located( locator) visibility_of_element_located = lambda: ec.visibility_of_element_located( locator) element_to_be_clickable = lambda: ec.element_to_be_clickable(locator) element_to_be_selected = lambda: ec.element_to_be_selected( self.find_element_helper.get_element(locator)) text_to_be_present_in_element = lambda: ec.text_to_be_present_in_element( locator, text) title_is = lambda: ec.title_is(text) title_contains = lambda: ec.title_contains(text) unknown_waiter = lambda: 'Неправильный тип ожидания' condition = wait_condition functions = { 'presence_of_element_located': presence_of_element_located, 'visibility_of_element_located': visibility_of_element_located, 'element_to_be_clickable': element_to_be_clickable, 'element_to_be_selected': element_to_be_selected, 'text_to_be_present_in_element': text_to_be_present_in_element, 'title_is': title_is, 'title_contains': title_contains } return functions.get(condition, unknown_waiter)()
def wait_until_element_to_be_selected(self, locator, *args): by, value = self.format_locator(locator, *args) try: message = "Unable to get the element to be clickable by {0}: '{1}' in the page '{2}'".format(by, value, self._driver.current_url) except WebDriverException: message = "Unable to get the element to be clickable by {0}: '{1}'".format(by, value) return self.until(EC.element_to_be_selected((by, value)), message)
def test_comment_on_favorite_source_triggers_notification( driver, user, user2, public_source ): driver.get(f'/become_user/{user.id}') driver.get("/profile") # Enable browser notifications for favorite source comments driver.click_xpath('//*[@name="comments"]', wait_clickable=False) checkbox_el = driver.wait_for_xpath('//*[@name="comments"]') WebDriverWait(driver, 3).until(EC.element_to_be_selected(checkbox_el)) # Make public_source a favorite driver.get(f"/source/{public_source.id}") driver.click_xpath(f'//*[@data-testid="favorites-exclude_{public_source.id}"]') driver.wait_for_xpath(f'//*[@data-testid="favorites-include_{public_source.id}"]') # Become user2 and submit comment on source driver.get(f'/become_user/{user2.id}') driver.get(f"/source/{public_source.id}") add_comment_and_wait_for_display(driver, "comment text") # Check that notification was created driver.get(f'/become_user/{user.id}') driver.get("/") driver.wait_for_xpath("//span[text()='1']") driver.click_xpath('//*[@data-testid="notificationsButton"]') driver.wait_for_xpath('//*[text()="New comment on your favorite source "]')
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 test_explicitwait(self): #导入堆栈类 import traceback 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,NoSuchElementException url ='F:\gitstorehouse\selenium3.0\webdriverAPI接口\测试页面\显式等待验证.html' self.driver.get(url) try: wait =WebDriverWait(self.driver,10,0.2) wait.until(EC.title_is('你喜欢的苹果')) print('网页标题你喜欢的苹果') element = WebDriverWait(self.driver,10).until(lambda x:x.find_element_by_xpath('//input[@value="Display alert box"]')) element.click() #等待alert框出现 alert = wait.until(EC.alert_is_present()) print(alert.text) #确认警告消息 alert.accept() peach = self.driver.find_element_by_id('peach') #判断复选框是能选中 peachelement = wait.until(EC.element_to_be_selected(peach)) print('下拉列表的选项‘桃子’目前处于选中状态') wait.until(EC.element_to_be_clickable((By.ID,'check'))) print('复选框可见并且能被单选') except TimeoutException as e : print(traceback.print_exc()) except NoSuchElementException as e: print(traceback.print_exc()) except Exception as e: print(traceback.print_exc())
def test_wait(self): time.sleep(3) WebDriverWait(self.driver, 10).until( expected_conditions.visibility_of_element_located(By.XPATH, '//')) WebDriverWait(self.driver, 10).until( expected_conditions.element_to_be_selected(By.XPATH, '//')) WebDriverWait(self.driver, 10).until( expected_conditions.presence_of_element_located(By.XPATH, '//'))
def wait_ele_to_be_selected(self, loc, timeout=10, poll_frequency=0.5): self.log.info(f"等待元素可被选择!---{loc[-1]}---") try: WebDriverWait(self.driver, timeout, poll_frequency).until(EC.element_to_be_selected(loc)) except TimeoutError as e: self.save_web_screenshots() self.log.error(f"等待元素可被选择报错!---{loc[-1]}---") raise e
def appointment_search(): global num driver.get(form_url) office_id = [] # Find all values of the offices to iterate through. 2 different ways to do it. # offices = driver.find_element_by_name('publicacionesForm:oficina') # office_id.append(offices.find) # offices = str(offices[0]).split('\n') # offices.pop(0) offices = driver.find_element(By.NAME, 'publicacionesForm:oficina') selector = Select(offices) # Waiting for the values to load loading = WebDriverWait(driver, 10).until( EC.element_to_be_selected(selector.options[0])) options = selector.options for index in range(1, len(options) - 1): office_id.append(options[index].text) # Select an office for appointment. Should iterate through all options. drop_down1 = Select(driver.find_element_by_id("publicacionesForm:oficina")) drop_down1.select_by_visible_text(office_id[num]) # Select specific appointment type. try: drop_down2 = Select( driver.find_element_by_name('publicacionesForm:tipoTramite')) drop_down2.select_by_value('3') # This value is for license swap. except NoSuchElementException: time.sleep(5) num += 1 appointment_search() # Select country. drop_down3 = Select(driver.find_element_by_name('publicacionesForm:pais')) drop_down3.select_by_value('21') # This specific value is for Venezuela. # Click search. search_button = driver.find_element_by_name('publicacionesForm:j_id70') search_button.click() # If there is no available appointment, start a loop. error_msg = driver.find_element_by_class_name('msgError') if error_msg: num += 1 if num == len(office_id) - 1: num = 0 time.sleep(10) appointment_search() else: messagebox.showinfo('Success.', 'Appointment found.')
def testExpectedConditionElementToBeSelected(self): self._loadPage("formPage") element = self.driver.find_element_by_id('checky') try: WebDriverWait(self.driver, 0.7).until(EC.element_to_be_selected(element)) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass
def test_searchGoogle_2(self): self.driver.get("https://www.google.com") self.driver.find_element_by_xpath("//*[@name='q']").send_keys( "Hello World again") time.sleep(3) wait = webdriver(self.driver, 10) element = wait.until(expected_conditions.element_to_be_selected(By)) print(self.driver.title) self.assertEquals("Google", self.driver.title)
def waitDriver(method, target, state): """ Overview state別に指定要素の描画を待つ Args method(string): 要素確認方法(xpath/id/name/linktext) target(string): 対象の要素(id,xpath,name,linktext等) state(string): 確認内容(locate,click,select,frame等) Return なし Raises: TimeoutException: 指定秒数待機しても要素が確認できなかった場合に発生 """ bymethod = { 'xpath': By.XPATH, 'id': By.ID, 'name': By.NAME, 'linktext': By.LINK_TEXT } try: if state == 'locate': WebDriverWait(driver, TIMEOUTSEC).until( EC.presence_of_element_located((bymethod[method], target))) elif state == 'click': WebDriverWait(driver, TIMEOUTSEC).until( EC.element_to_be_clickable((bymethod[method], target))) elif state == 'select': WebDriverWait(driver, TIMEOUTSEC).until( EC.element_to_be_selected((bymethod[method], target))) elif state == 'text': WebDriverWait(driver, TIMEOUTSEC).until( EC.text_to_be_present_in_element((bymethod[method], target))) elif state == 'vlocate': WebDriverWait(driver, TIMEOUTSEC).until( EC.visibility_of_element_located((bymethod[method], target))) elif state == 'frame': WebDriverWait(driver, TIMEOUTSEC).until( EC.frame_to_be_available_and_switch_to_it( (bymethod[method], target))) else: logger.error(str(getCurLineNo()) + ' 引数エラー state:' + state) raise ValueError except exceptions.TimeoutException as e: logger.error( str(getCurLineNo()) + ' 画面表示タイムアウトエラー method:' + method + ' target:' + target + ' state:' + state) raise (e) except exceptions.UnexpectedAlertPresentException as e: logger.error( str(getCurLineNo()) + ' UnexpectedAlertPresentException発生 ' + str(e)) raise (e) except Exception as e: logger.error(str(getCurLineNo()) + ' 想定外の例外発生 ' + str(e)) raise (e)
def get_isSelect(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_to_be_selected( WebDriver.find_element(By.ID, value))) return element elif by == 'name': element = wait.until( EC.element_to_be_selected( WebDriver.find_element(By.NAME, value))) return element elif by == 'className': element = wait.until( EC.element_to_be_selected( WebDriver.find_element(By.CLASS_NAME, value))) return element elif by == 'css': element = wait.until( EC.element_to_be_selected( WebDriver.find_element(By.CSS_SELECTOR, value))) return element elif by == 'tagName': element = wait.until( EC.element_to_be_selected( WebDriver.find_element(By.TAG_NAME, value))) return element elif by == 'linkText': element = wait.until( EC.element_to_be_selected( WebDriver.find_element(By.LINK_TEXT, value))) return element else: element = wait.until( EC.element_to_be_selected( WebDriver.find_element(By.XPATH, value))) return element else: xpath = "//*[text()='{}']".format(way) element = wait.until( EC.element_to_be_selected( WebDriver.find_element(By.XPATH, xpath))) return element
def wait_util_selected(self, locat_type, locate_value, secs=10): try: if locat_type.lower() in self.locationTypeDict: element = WebDriverWait(self.driver, secs).until( EC.element_to_be_selected(( self.location_type_dict[locat_type], locate_value))) return element else: raise TypeError(u"未找到定位方式,请确认定位方法是否正确") except Exception as e: raise e
def wait_for_element_selector(self, name=None, css_selector=None, timeout=10): """ An expectation for checking the selection is selected. element is WebElement object """ if name: css_selector = self.find_ui_node(name)['selector'] WebDriverWait(self.context.browser, timeout).until( EC.element_to_be_selected((By.CSS_SELECTOR, css_selector)))
def all_studios_list(): driver.get(url) check_studio = driver.find_element(By.NAME, "m_act[company]") all_studios = Select(check_studio) # wating for the values to load element = WebDriverWait(driver, 10).until( EC.element_to_be_selected(all_studios.options[0])) studios = all_studios.options for index in range(2, len(studios)): studio_list.append((studios[index].text)) studio_values.append((studios[index].get_attribute('value')))
def deactivateChoice(self, locatorType, locator): element = self.getElement(locatorType, locator) state = element.is_selected() try: if not state: self.warning("Element is already deselected") pass else: self.wait.until_not(EC.element_to_be_selected(element)) except: self.logCritical(f"Cannot deselect the element ", locatorType, locator)
def judge_is_selected(self, element, timeout=15, poll=0.5): """ 判断某个元素是否被选中 :param element: 元素 :param timeout: 最大查找时间 :param poll: 间隔时间 :returns: 元素 """ try: WebDriverWait(self.driver, timeout, poll).until(EC.element_to_be_selected(element)) return True except Exception: return False