def testCanSwitchToWindowByName(driver, pages): pages.load("xhtmlTest.html") handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) driver.switch_to.window("result") assert driver.title == "We Arrive Here"
def test_clicking_on_abutton_that_closes_an_open_window_does_not_cause_the_browser_to_hang(driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.NAME, "windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.find_element(By.ID, "close").click() driver.switch_to.window(current) driver.find_element(By.ID, "linkId")
def switch_window(self, index='-1'): handles = self.driver.window_handles try: WebDriverWait(self.driver, 20, 0.5).until(EC.new_window_is_opened(handles)) except: MyLog.error("未出现新的窗口。") handles = self.driver.window_handles if index == '-1': self.driver.switch_to.window(handles[-1]) elif index != None and 0 <= int(index) < len(handles): self.driver.switch_to.window(handles[index])
def wait_and_switch_to_new_window(self, current_handles) -> None: """ Cambia el contexto a la última pestaña abierta Args: current_handles: cantidad de ventanas actuales Returns: None """ self.wait.until(ec.new_window_is_opened(current_handles)) self.driver.switch_to.window(self.driver.window_handles[-1])
def testClickingOnAButtonThatClosesAnOpenWindowDoesNotCauseTheBrowserToHang(self, driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element_by_name("windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.find_element_by_id("close").click() driver.switch_to.window(current) driver.find_element_by_id("linkId")
def testCanCallGetWindowHandlesAfterClosingAWindow(self, driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element_by_name("windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.find_element_by_id("close").click() WebDriverWait(driver, 3).until(EC.number_of_windows_to_be(1))
def testClickingOnAButtonThatClosesAnOpenWindowDoesNotCauseTheBrowserToHang(driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.NAME, "windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.find_element(By.ID, "close").click() driver.switch_to.window(current) driver.find_element(By.ID, "linkId")
def testCanCallGetWindowHandlesAfterClosingAWindow(driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.NAME, "windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.find_element(By.ID, "close").click() WebDriverWait(driver, 3).until(EC.number_of_windows_to_be(1))
def wait_for_new_window(self, windows: Optional[Sequence]=None): """ Args: windows (Sequence): """ if windows is None: windows = self.driver.window_handles return WebDriverWait(self.driver, self.timeout).until( EC.new_window_is_opened(windows) )
def test_should_throw_no_such_window_exception_on_an_attempt_to_get_its_handle(driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.close() with pytest.raises(NoSuchWindowException): driver.current_window_handle
def testShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle(driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.close() with pytest.raises(NoSuchWindowException): driver.current_window_handle
def new_window_is_opened(self, current_handles, **kwargs): """ An expectation that a new window will be opened and have the number of windows handles increase Arguments current_handles (obj): current handle object timeout (int): seconds to wait for message (str): message to display if timed out kwargs (dict): any other argument for WebDriverWait() api """ condition = EC.new_window_is_opened(current_handles) return self(condition, **kwargs)
def testShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle(self, driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.close() with pytest.raises(NoSuchWindowException): driver.current_window_handle
def switch_window(self, name=None, fqc=20): """ 切换窗口,有name切换至该name的窗口,没有则切换最新 :param name: :param fqc: :return: """ if name is None: current_handle = self.driver.current_window_handle WebDriverWait(self.driver, fqc).until(EC.new_window_is_opened(current_handle)) handles = self.driver.window_handles return self.driver.switch_to.window(handles[-1]) return self.driver.switch_to.window()
def testCanCallGetWindowHandlesAfterClosingAWindow(self, driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element_by_name("windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.find_element_by_id("close").click() all_handles = driver.window_handles assert 1 == len(all_handles)
def testShouldThrowNoSuchWindowExceptionOnAnyElementOperationIfAWindowIsClosed(self, driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) element = driver.find_element_by_tag_name("body") driver.close() with pytest.raises(NoSuchWindowException): element.text
def testShouldThrowNoSuchWindowExceptionOnAnyElementOperationIfAWindowIsClosed(driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) element = driver.find_element(By.TAG_NAME, "body") driver.close() with pytest.raises(NoSuchWindowException): element.text
def test_8(driver): wait = WebDriverWait(driver, 4) driver.get('http://localhost/litecart/admin') driver.find_element_by_css_selector( 'input[class=form-control][name=username]').send_keys('admin') driver.find_element_by_css_selector( 'input[class=form-control][name=password]').send_keys('admin') driver.find_element_by_css_selector( 'button[class="btn btn-default"][name=login]').click() driver.find_element_by_css_selector('body div ul li#app-countries').click() add_new_country = driver.find_element_by_css_selector( 'a[class="btn btn-default"]') assert add_new_country.text == 'Add New Country' add_new_country.click() wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, 'h1'))) ex_links = driver.find_elements_by_css_selector( 'a[href] i[class="fa fa-external-link"]') assert len(ex_links) == 9 current_tab = driver.current_window_handle current_tabs = driver.window_handles for link in ex_links: link.click() wait.until(ec.new_window_is_opened(current_tabs)) updated_tabs = driver.window_handles new_tab = [tab for tab in updated_tabs if tab not in current_tabs][0] driver.switch_to_window(new_tab) wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, 'h1'))) current_tabs = updated_tabs driver.switch_to.window(current_tab) while True: external_tabs = [ tab for tab in driver.window_handles if tab != current_tab ] if not external_tabs: driver.switch_to.window(current_tab) break driver.switch_to.window(external_tabs[-1]) driver.close() driver.find_element_by_css_selector( 'i[class="fa fa-sign-out fa-lg"]').click() wait.until( ec.visibility_of_element_located( (By.CSS_SELECTOR, 'body div[id=box-login]')))
def testShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle(self, driver, pages): if driver.capabilities['browserName'] == 'firefox' and driver.w3c: pytest.xfail("Marionette Doesnt Throw: https://bugzilla.mozilla.org/show_bug.cgi?id=1309173") pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.close() with pytest.raises(NoSuchWindowException): driver.current_window_handle
def check_links_on_country_page(wd): wait = WebDriverWait(wd, 10) open_new_country_creation_form(wd) links_list = wd.find_elements_by_css_selector("i.fa.fa-external-link") main_window = wd.current_window_handle opened_windows = wd.window_handles for link in links_list: link.click() wait.until(EC.new_window_is_opened(opened_windows)) new_windows = wd.window_handles for window in opened_windows: new_windows.remove(window) wd.switch_to_window(new_windows[0]) wd.close() wd.switch_to_window(main_window)
def testThatAccessingFindingAnElementAfterWindowIsClosedAndHaventswitchedDoesntCrash(self, driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element_by_name("windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) with pytest.raises(WebDriverException): driver.find_element_by_id("close").click() all_handles = driver.window_handles assert 1 == len(all_handles) driver.find_element_by_id("close") driver.switch_to.window(current)
def wait_windows_and_switch_to_it(self,current_handles,wait_time=20,poll_frequency=0.5,model_name=''): try: logger.info('等待新窗口打开') WebDriverWait(self.driver,wait_time,poll_frequency).until(EC.new_window_is_opened(current_handles)) except: logger.exception('等待打开新窗口失败') self._get_screenShot(model_name) raise try: logger.info('切换到新打开的窗口') cur_handles = self.driver.window_handles self.driver.switch_to.window(cur_handles[-1]) except: logger.exception('切换到新打开的窗口失败') self._get_screenShot(model_name) raise
def new_window_is_opened(self, current_handles, driver=None, timeout=30): ''' An expectation that a new window will be opened and have the number of windows handles increase ''' driver = driver or self.driver try: element = WebDriverWait(driver, timeout).until( EC.new_window_is_opened(current_handles)) return element except Exception as e: # print("wait_for_element timeout: ") print(str(e)) return None
def testThatAccessingFindingAnElementAfterWindowIsClosedAndHaventswitchedDoesntCrash(driver, pages): pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.NAME, "windowThree").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) with pytest.raises(WebDriverException): driver.find_element(By.ID, "close").click() all_handles = driver.window_handles assert 1 == len(all_handles) driver.find_element(By.ID, "close") driver.switch_to.window(current)
def test_one(self): self.driver.get( "http://litecart.stqa.ru/admin/?app=countries&doc=edit_country") main_window_handle = self.driver.current_window_handle xpath = """//a[.//*[contains(@class, 'fa fa-external-link')]]""" refs = self.driver.find_elements_by_xpath(xpath) for element in refs: old_handles = self.driver.window_handles element.click() self.wait.until(EC.new_window_is_opened(old_handles)) new_handles = self.driver.window_handles new_window_handle = self._get_new_window_handle( old_handles, new_handles) self.driver.switch_to.window(new_window_handle) self.driver.close() self.driver.switch_to.window(main_window_handle)
def main(): driver = webdriver.Chrome() try: driver.get( "http://localhost/litecart/admin/?app=countries&doc=countries") wait = WebDriverWait(driver, 10) # seconds wait.until(EC.title_contains("My Store")) fld = driver.find_element_by_name("username") fld.send_keys("admin") fld = driver.find_element_by_name("password") fld.send_keys("111") btn = driver.find_element_by_name("login") btn.click() wait.until(EC.title_contains("Countries")) btn = driver.find_element_by_css_selector( "#content a.button") # кнопка Добавить страну time.sleep(1) # без этого в Chrome кликается не всегда btn.click() wait.until(EC.title_contains("Add New Country")) links = driver.find_elements_by_css_selector( "#content a[target=_blank]:not([title])") if not links: raise Exception("Ссылок в другие окна нет") original_window = driver.current_window_handle for lnk in links: existing_windows = driver.window_handles lnk.click() if wait.until(EC.new_window_is_opened(existing_windows)): new_window = find_opened_window_handle(driver, existing_windows) driver.switch_to.window(new_window) print("Открыто " + driver.title) driver.close() driver.switch_to.window(original_window) else: raise Exception("Новое окно не открылось") print("Успешно") finally: driver.quit()
def testShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle( self, driver, pages): if driver.capabilities['browserName'] == 'firefox' and driver.w3c: pytest.xfail( "Marionette Doesnt Throw: https://bugzilla.mozilla.org/show_bug.cgi?id=1309173" ) pages.load("xhtmlTest.html") current = driver.current_window_handle handles = driver.window_handles driver.find_element(By.LINK_TEXT, "Open new window").click() WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles)) handles = driver.window_handles handles.remove(current) driver.switch_to.window(handles[0]) driver.close() with pytest.raises(NoSuchWindowException): driver.current_window_handle
def Enter_Game(self): # Verify Old Tab window_before = self.driver.window_handles[0] print("<li>" + "Click on Enter Game button" + "</li>" + "<br>") wait_enter_game = EC.element_to_be_clickable((By.XPATH, ProvidersElement.enter_the_game_button)) WebDriverWait(self.driver, 20).until(wait_enter_game) click_enter = self.driver.find_element_by_xpath(ProvidersElement.enter_the_game_button).click() waitnewpage = EC.new_window_is_opened(self.driver.window_handles) WebDriverWait(self.driver, 30).until(waitnewpage) # Verify New Tab self.driver.switch_to.window(self.driver.window_handles[1]) self.driver.implicitly_wait(10) # Assert Gaming Page game_url = self.driver.current_url r = requests.get(game_url) page_status = r.status_code print("The gaming page status is: " + str(page_status) + "<br>") self.assertEqual(page_status, 200, "Unable to access to gaming page.")
def click_links(self): wd = self.app.wd wait = self.wait main_window = self.get_main_window_id() print('\n' 'main_window =', main_window) elements = wd.find_elements_by_css_selector('i.fa.fa-external-link') for i in range(len(elements)): elements[i].click() new_id = self.get_new_window_id(main_window) wd.switch_to.window(new_id[0]) wait.until(EC.new_window_is_opened(new_id)) k = wd.title wd.close() wd.switch_to.window(main_window) print('i =', i, 'title is=', k)
def Handle_delete_Conf_Win(self, confirmation): # childwindow = self.driver.window_handles[1] # self.driver.switch_to.window(childwindow) # print(self.driver.find_element_by_tag_name("h3").text) wait = WebDriverWait(self.driver, 15) wait.until(EC.new_window_is_opened((By.CLASS_NAME, "deleteConfModal"))) self.driver.switch_to.frame("deleteConfModal") win_title = self.driver.find_element_by_tag_name("h3").text print(win_title) #OrangeHRM - Confirmation Required delete_conf_msg = self.driver.find_element_by_class_name( "modal-body").text print(delete_conf_msg) if "Delete records?" in delete_conf_msg and confirmation == "Y": self.driver.find_element_by_id("dialogDeleteBtn").click() elif "Delete records?" in delete_conf_msg and confirmation == "N": self.driver.find_elemnent_by_class_name("btn reset").click()
def test_example(driver): # driver.maximize_window() driver.get("http://localhost/litecart/admin/") driver.delete_all_cookies() driver.get("http://localhost/litecart/admin/") driver.find_element_by_name("username").send_keys("admin") driver.find_element_by_name("password").send_keys("admin") # driver.find_element_by_name("remember_me").click() driver.find_element_by_name("login").click() WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, "#box-apps-menu"))) driver.find_element_by_css_selector( '#box-apps-menu a[href*="countries"]').click() WebDriverWait(driver, 10).until(\ EC.presence_of_element_located((By.CSS_SELECTOR, '#content a[href*="edit_country"]'))) driver.find_element_by_css_selector( '#content a[href*="edit_country"]').click() WebDriverWait(driver, 10).until(\ EC.presence_of_element_located((By.CSS_SELECTOR, '#content'))) time.sleep(2) box = driver.find_elements_by_css_selector( '#content table a[href^="http"]') for elem in box: first_window = driver.current_window_handle win_handles = driver.window_handles #print('first_window ') #print(first_window) elem.click() WebDriverWait(driver, 10).until(EC.new_window_is_opened(win_handles)) two_windows = set(driver.window_handles) #print('two_windows ') #print(two_windows) two_windows.remove(first_window) #print('two_windows remove(first_window) ') #print(two_windows) for elem in two_windows: second_window = elem driver.switch_to_window(second_window) time.sleep(4) driver.close() time.sleep(2) driver.switch_to_window(first_window)
def open_new_window(self, desc=None): """ 打开新窗口 :param desc: 元素的描述 :return: """ wins = self.driver.window_handles try: WebDriverWait(self.driver, 15, 0.5).until( expected_conditions.new_window_is_opened(wins)) win = self.driver.window_handles self.driver.switch_to.window(win[-1]) except Exception as e: log.error('新窗口--【{}】--打开失败'.format(desc)) log.exception(e) self.error_save_screenshot(desc) raise e else: log.info('新窗口--【{}】--打卡成功'.format(desc))
def click_links_on_country_page(self, countries_links_list): wd = self.app.wd link = random.choice(countries_links_list) wd.get(link) links_target_blank = wd.find_elements_by_css_selector( "#content form a[target='_blank']") for link in links_target_blank: original_window = wd.current_window_handle existing_windows = wd.window_handles new_list_windows = [] link.click() wait = WebDriverWait(wd, 5) if wait.until(ec.new_window_is_opened(existing_windows)): new_list_windows = wd.window_handles new_list_windows.remove(original_window) new_window = new_list_windows[0] wd.switch_to.window(new_window) wd.close() wd.switch_to.window(original_window)
def opening_new_windows(self): main_window = self.driver.current_window_handle old_windows = self.driver.window_handles links = self.wait.until( EC.presence_of_all_elements_located( (By.CSS_SELECTOR, 'i.fa.fa-external-link'))) for i in range(0, len(links)): str_links = self.wait.until( EC.presence_of_all_elements_located( (By.CSS_SELECTOR, 'i.fa.fa-external-link'))) str_links[i].click() self.wait.until(EC.new_window_is_opened(old_windows)) new_windows = self.driver.window_handles result = list(set(new_windows) - set(old_windows)) new_window = result[0] self.driver.switch_to.window(new_window) self.driver.close() self.driver.switch_to.window(main_window) return
def check_external_links_on_edit_page(self): wd = self.app.wd wait = self.app.wait main_window = wd.current_window_handle old_windows = wd.window_handles links = self.get_external_links_on_edit_page() print("Amount of links to test is: %s" % str(len(links))) for link in links: print("URL under test is: %s" % link.get_attribute("href")) link.click() wait.until(EC.new_window_is_opened(old_windows)) new_window = self.there_is_window_other_than(old_windows) wd.switch_to.window(new_window) if "/litecart/admin" in wd.current_url: print("The url in current window is wrong") return False wd.close() wd.switch_to.window(main_window) return True
def test_example(driver): driver.get("http://localhost/litecart/admin/") driver.find_element_by_name("username").send_keys("admin") driver.find_element_by_name("password").send_keys("admin") driver.find_element_by_name("login").click() driver.get("http://localhost/litecart/admin/?app=countries&doc=countries") driver.find_element_by_css_selector(".row a").click() main_window = driver.current_window_handle ex_links = driver.find_elements_by_css_selector(".fa.fa-external-link") for i in ex_links: i.click() new_window = [i for i in driver.window_handles if i != main_window] wait.until(expected_conditions.new_window_is_opened(new_window)) for window in new_window: driver.switch_to.window(window) driver.close() driver.switch_to.window(main_window)
def searchKeyword(self): search_form_path = "//input[@id='kw']" #找到百度首页搜索栏 WebDriverWait(self.browser, 60, 1).until( EC.visibility_of_element_located( (By.XPATH, search_form_path))) #判断搜索框可见 self.browser.find_element_by_xpath(search_form_path).send_keys( "selenium webdriver") #搜索框传入指定参数 search_button_path = "//input[@id='su']" #找到搜索输入框元素 WebDriverWait(self.browser, 60, 1).until( EC.element_to_be_clickable( (By.XPATH, search_button_path))) # 判断百度一下按钮可用 self.browser.find_element_by_xpath( search_button_path).click() #点击百度一下按钮 windows = self.browser.window_handles result_selenium_path = "//div[text()=' The biggest change in ']//preceding-sibling::h3//a" #找到官网链接结果元素 WebDriverWait(self.browser, 60, 1).until( EC.element_to_be_clickable( (By.XPATH, result_selenium_path))) # 判断官网链接可点击 self.browser.find_element_by_xpath( result_selenium_path).click() #点击官网链接关键字元素 WebDriverWait(self.browser, 60, 1).until(EC.new_window_is_opened(windows)) # 一用就报错,用不好 #获取当前所有窗口 windows = self.browser.window_handles #切换到最新打开的窗口 self.browser.switch_to.window(windows[-1]) download_button_path = "//div[@class='downloadBox']" #定位到新网页右侧下载按钮位置 #download_button_path="//li[@id='menu_download']" #定位到新网页上方下载按钮位置 WebDriverWait(self.browser, 60, 1).until( EC.element_to_be_clickable( (By.XPATH, download_button_path))) # 判断download按钮可点击 self.browser.find_element_by_xpath( download_button_path).click() #点击download按钮 time.sleep(3) #等待3秒查看下载界面信息 self.browser.close() #关闭当前窗口 self.browser.switch_to.window(windows[0]) #切换到原始窗口 self.browser.close() #关闭原始窗口 self.browser.quit() #关闭浏览器