def auth_with_google(driver, email=EMAIL, password=PASSWORD): """ I don't have Yandex account so authenticate with Google """ wait = WebDriverWait(driver, 10) driver.get(BASE_URL) driver.find_element_by_class_name('button_enter').click() wait.until( expected_conditions.element_to_be_clickable( (By.CLASS_NAME, 'passp-social-block__list-item-gg'))) original_window = driver.current_window_handle assert len(driver.window_handles) == 1 driver.find_element_by_class_name( 'passp-social-block__list-item-gg').click() wait.until(expected_conditions.number_of_windows_to_be(2)) for window_handle in driver.window_handles: if window_handle != original_window: driver.switch_to.window(window_handle) break _fill_in_and_hit_return(driver, 'identifier', email) time.sleep(2) _fill_in_and_hit_return(driver, 'password', password) wait.until(expected_conditions.number_of_windows_to_be(1)) driver.switch_to.window(original_window) time.sleep(5)
def test_login_in_google_window(self): self.driver.implicitly_wait(15) winHandleBefore = self.driver.current_window_handle main = page.MainPage(self.driver) main.click_button() main.click_button() wait = WebDriverWait(self.driver, 10) wait.until(EC.number_of_windows_to_be(2)) for handle in self.driver.window_handles: self.driver.switch_to.window(handle) google = page.GooglePage(self.driver) login = self.driver.find_element_by_id("identifierId") login.send_keys("*****@*****.**") google.click_next() password = self.driver.find_element_by_name("password") password.send_keys("Nwta1234!") google.click_next2() wait = WebDriverWait(self.driver, 10) wait.until(EC.number_of_windows_to_be(1)) self.driver.switch_to.window(winHandleBefore) main.click_button() assert "Log out" not in self.driver.page_source
def run(driver, link): main_window = driver.current_window_handle ActionChains(driver).key_down(Keys.CONTROL).click(link).key_up(Keys.CONTROL).perform() try: WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) except TimeoutException: print('try click again') try: ActionChains(driver).key_down(Keys.CONTROL).click(link).key_up(Keys.CONTROL).perform() WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) except TimeoutException: print('cannot click') return None driver.switch_to.window(driver.window_handles[1]) try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="content"]/div/div[1]/h5[@class="min_rec"]'))) except TimeoutException: print('not found song name (run method)') song_name = get_song_name(driver) if song_name == False: song_name = "incorrect name" btn = wait_on_click(driver, '//*[@id="download"]') status = dawnload_song(driver, btn) if status == False: print('This is song is not downloaded: ', song_name) song_rename(song_name) driver.close() WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(1)) driver.switch_to.window(main_window)
def test_new_window(driver): wait = WebDriverWait(driver, 10) admin_login(driver) driver.get("http://localhost/litecart/admin/?app=countries&doc=countries") driver.find_element(By.XPATH, '//a[contains(., " Add New Country")]').click() extra_links_list = driver.find_elements(By.CSS_SELECTOR, '.fa.fa-external-link') i = 0 while i < len(extra_links_list): old_windows_list = driver.window_handles main_window = driver.current_window_handle extra_links_list[i].click() wait.until(EC.new_window_is_opened(old_windows_list)) assert wait.until(EC.number_of_windows_to_be(2)) test_windows_list = driver.window_handles for window in test_windows_list: if window not in old_windows_list: new_window = window driver.switch_to_window(new_window) print(driver.title) driver.close() driver.switch_to_window(main_window) assert wait.until(EC.number_of_windows_to_be(1)) i += 1
def download_pdfs(driver): """ Finds and downloads all pdfs on a moodle class page Arguments: :type driver webdriver Selenium Webdriver. """ # Path to all 'a' tagged embedded links in the 'topics' list xpath = "//ul[@class='topics']//child::a" elements = driver.find_elements_by_xpath(xpath) # Scan all links for 'resources' and 'folders' # This should pick up all pdf files, and ignore all other junk links # By inspection, links on moodle follow this format: https://moodle.rose-hulman.edu/mod/x/view.php?id=y # where x = resource, folder, or url; x occurs at index 4 with split('/') command # and y = some id number for element in elements: # Ensure all elements on xpath are loaded to avoid Stale Element Exception wait = WebDriverWait(driver, 10) wait.until(cond.visibility_of_all_elements_located((By.XPATH, xpath))) # Access the link link = element.get_attribute("href") link_items = link.split('/') # Finds all links to resource files if ((link_items[4] == "resource") or (link_items[4] == "folder")): windows_before = driver.current_window_handle # Open and switch to link in new tab driver.execute_script("window.open('%s')" % link) WebDriverWait(driver, 10).until(cond.number_of_windows_to_be(2)) windows_after = driver.window_handles new_window = [x for x in windows_after if x != windows_before][0] # Switching to a new tab will auto-download pdf files and close the # window under the current chrome settings driver.switch_to_window(new_window) # If the window doesn't close, then it wasn't a pdf file; skip past it or open folder; wait 1 second try: WebDriverWait(driver, 1).until(cond.number_of_windows_to_be(1)) driver.switch_to_window(windows_before) except TimeoutException as e: if (link_items[4] == "folder"): btn_xpath = "//section[@id='region-main']//child::button[1]" WebDriverWait(driver, 10).until( cond.element_to_be_clickable((By.XPATH, btn_xpath))) dwnld_btn = driver.find_element_by_xpath(btn_xpath) dwnld_btn.click() driver.close() driver.switch_to_window(windows_before) else: print("Found non-pdf file. Skipping. . .") driver.close() driver.switch_to_window(windows_before) pass
def function(): """Функция проверки на открытие новых окон""" driver.get(COUNTRY_URL) driver.find_element_by_css_selector('#content div a').click() link_list = driver.find_elements_by_xpath('//*[@id="content"]//td/a/i') main_window = driver.current_window_handle #текущее окно print('Главное окно:', main_window) windows_list_OLD = [] windows_list_NEW = [] error_list = [] x = 0 y = 0 #Счетчик открывшихся окон #По списку ссылок на странице for link in link_list: windows_list_OLD.append(driver.window_handles) #Список старых окон #Механизм повтора события при закрытии алерта try: driver.find_elements_by_xpath( '//*[@id="content"]//td/a/i')[x].click() wait.until(EC.number_of_windows_to_be(2)) windows_list_NEW.append( driver.window_handles ) # Список новых окон после клика по ссылке except UnexpectedAlertPresentException: driver.find_elements_by_xpath( '//*[@id="content"]//td/a/i')[x].click() wait.until(EC.number_of_windows_to_be(2)) windows_list_NEW.append( driver.window_handles ) # Список новых окон после клика по ссылке result = list(set(windows_list_NEW[0]) ^ set(windows_list_OLD[0]) ) #Получение нового элемента из списка (новое окно) if len( result ) >= 1: #В момент возникновения алерта, в список ничего не добавляется и он пуст. Делаем проверку на [] new_window = driver.switch_to.window( result[0]) #Переключаемся в новое окно print('Новое окно:', result[0]) driver.close() y += 1 else: print('Ошибка: Алерт или ссылка открылась не в главном окне') error_list.append(driver.window_handles) driver.switch_to.window(main_window) #переключаемся в главное окно #Обнуляем списки для следующих итераций windows_list_NEW = [] windows_list_OLD = [] x += 1 if len(link_list) == y: print('ТЕСТ ОК. КОЛ-ВО ССЫЛОК НА СТРАНИЦЕ И ОТКРЫТЫХ ОКОН СОВПАДАЮТ') print("Кол-во открытых окон: ", y, " ," " Кол-во ссылок:", len(link_list)) else: print('Опять что-то не так') print("Кол-во открытых окон: ", y, "," " кол-во ссылок:", len(link_list))
def save_as_pdf(blog_posts): x = 0 for post in blog_posts: x += 1 print(f"Saving [{x}] {post}") launch(post) driver.execute_script('window.print();') WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) WebDriverWait(driver, 180).until(EC.number_of_windows_to_be(1))
def create_report(course, driver): """ Create a map of incomplete assignments and quizzes @param course: Course name @type course: str @param driver: Web driver @type driver: driver @return: map of assignment and quizzes @rtype: dict """ quiz_info = [] assignment_info = [] select_course(course, driver) incomplete_quizzes_elements = [] incomplete_assignments = [] try: incomplete_quizzes_elements = get_incomplete_quizzes(driver) incomplete_assignments = get_incomplete_assignments(driver) except TimeoutException: pass # print(f"incomplete quiz :{[x.text for x in incomplete_quizzes_elements]}") # print(f"incomplete assign : {[x.text for x in incomplete_assignments]}") for quiz in incomplete_quizzes_elements: ActionChains(driver).key_down(Keys.CONTROL).click(quiz).key_up( Keys.CONTROL).perform() WebDriverWait(driver, 10).until( EC.number_of_windows_to_be(len(incomplete_quizzes_elements) + 1)) tabs = driver.window_handles for i in range(1, len(tabs)): driver.switch_to.window(tabs[i]) quiz_info.append(extract_quiz_info(driver, course)) driver.close() driver.switch_to.window(tabs[0]) for assignment in incomplete_assignments: ActionChains(driver).key_down(Keys.CONTROL).click(assignment).key_up( Keys.CONTROL).perform() WebDriverWait(driver, 10).until( EC.number_of_windows_to_be(len(incomplete_assignments) + 1)) tabs = driver.window_handles for i in range(1, len(tabs)): driver.switch_to.window(tabs[i]) assignment_info.append(extract_assign_info(driver, course)) driver.close() driver.switch_to.window(tabs[0]) driver.back() return {"quizzes": quiz_info, "assignments": assignment_info}
def check_stock(self, new_tab=False): stock = False if new_tab: windows_before = self.browser.window_handles self.browser.execute_script(f'window.open("{self.product}")') wait(self.browser, 10).until(EC.number_of_windows_to_be(2)) new_window = [ x for x in self.browser.window_handles if x not in windows_before ][0] self.browser.switch_to_window(new_window) if len( self.browser.find_elements_by_xpath( '//button[@data-test="orderPickupButton"]')) > 0 or len( self.browser.find_elements_by_xpath( '//button[@data-test="shipItButton"]')) > 0: #select quantity quantityButton = '//button[@data-test="custom-quantity-picker"]' wait(self.browser, 15).until( EC.presence_of_element_located((By.XPATH, quantityButton))) self.find_and_click(quantityButton) quantityThreeOption = '//*[@id="options"]/li[3]' wait(self.browser, 15).until( EC.presence_of_element_located( (By.XPATH, quantityThreeOption))) self.find_and_click(quantityThreeOption) wait(self.browser, 15).until( EC.presence_of_element_located( (By.XPATH, '//button[@data-test="shipItButton"]'))) button = self.browser.find_element_by_xpath( '//button[@data-test="shipItButton"]') if button: self.browser.execute_script( "return arguments[0].scrollIntoView(true);", button) button.click() try: wait(self.browser, 10).until( EC.text_to_be_present_in_element(( By.XPATH, '//div[@data-test="errorContent"]/h2' ), 'Item not added to your cart. Something went wrong, please try again.' )) except: stock = True stock = False if new_tab: self.browser.close() wait(self.browser, 10).until(EC.number_of_windows_to_be(1)) old_window = self.browser.window_handles[0] self.browser.switch_to_window(old_window) return False return stock
def wait_for_expected_number_of_open_windows( ctx: Context, expected_window_count: int, timeout: Union[int, None] = None, ) -> bool: """Wait until the expected number of windows are open. Args: ctx: The behave context object. expected_window_count: The amount of windows expected to be open. timeout: seconds to wait for the element to appear or None. Default is set in the environment.py file. Raises: TimeoutException: if the element was not present after the timeout was reached Returns: True if element is present """ timeout = timeout or ctx.wait_timeout try: LOGGER.debug( f"Waiting for {expected_window_count} windows to be open") WebDriverWait(ctx.driver, timeout).until( EC.number_of_windows_to_be(expected_window_count)) LOGGER.debug( f"Successfully detected {expected_window_count} windows are open." ) return True except TimeoutException: raise TimeoutException( f"Only {len(ctx.driver.window_handles)} window(s) were found open." f" Expected to be {expected_window_count} windows.")
def click_extension_workshop(self): self.find_element(*self._extension_workshop_locator).click() self.wait.until(EC.number_of_windows_to_be(2)) new_tab = self.selenium.window_handles[1] self.selenium.switch_to_window(new_tab) self.wait.until( EC.visibility_of_element_located((By.CLASS_NAME, 'logo')))
def bbk(): account = ['ES6920950462413830261066','ES9720950461109100168147'] url = 'https://bbk.kutxabank.es/cs/Satellite/kb/es/negocios_y_empresas' browser.get(url) alert(text='Click ok after you ve logued in.', title='Kutxabank', button='OK') current = browser.window_handles[0] WebDriverWait(browser, 20).until(EC.number_of_windows_to_be(2)) newWindow = [window for window in browser.window_handles if window != current][0] browser.switch_to.window(newWindow) browser.find_element_by_id('divEntrar').click() waitElement('formPAS:j_id134:0:data1:0:j_id140:0:j_id144') browser.find_element_by_id('formPAS:j_id134:0:data1:0:j_id140:0:j_id144').click() time.sleep(4) browser.find_element_by_id('formCriterios:criteriosMovimientos:_1').click() time.sleep(5) try: browser.find_element_by_id('formListado:resourceExcel').click() rename_excel_file(user,'Kutxsabank-',account[0]) except: print('BBK: No hay movimientos en el periodo ingresado.') time.sleep(6) #cambio de cuenta browser.find_element_by_id('formMenuSuperior:PanelSuperior:2:itemMenuSuperior').click() waitElement('formPAS:j_id97:0:data1:1:j_id103:0:j_id108') browser.find_element_by_id('formPAS:j_id97:0:data1:1:j_id103:0:j_id108').click() time.sleep(5) try: browser.find_element_by_id('formListado:resourceExcel').click() rename_excel_file(user,'Kutxsabank-',account[1],dateFile) except: print('BBK: No hay movimientos en el periodo ingresado.') time.sleep(6) browser.close() browser.switch_to_window(current)
def goto_new_window(self): try: WebDriverWait(self.driver, 10).until(EC.number_of_windows_to_be(2)) self.driver.switch_to.window(self.driver.window_handles[1]) logger.info("Successfully go to new page window") except Exception as e: logger.error("Failed to go to new page window with %s" % e)
def processing_profile(self, driver, url): try: # тут обрабатываем аккаунт фотографа driver.execute_script( "window.open('{}', 'new_window')".format(url)) # ждем покаоткроется новая вкладка WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) main_w = driver.window_handles[0] child = driver.window_handles[1] # переходим в новую вкладку driver.switch_to.window(child) # что то делвем self.lg.info('Processing profile {} ...'.format( driver.current_url)) time.sleep( random.randint(int(self.data.get('pause_show_profile_min')), int(self.data.get('pause_show_profile_max')))) # просматриваем контакты if self.data.get('contacts') == 'on': self.show_contacts(driver) elif self.data.get('contacts') == 'rand': if random.randint(1, 2) == 1: # рандомно смотрим или нет self.show_contacts(driver) # закрываем вкладку driver.close() #переходим обратно driver.switch_to.window(main_w) return True except: self.lg.exception('processing_profile')
def show_any_urls(self, driver, xpah, countswindows=3): try: # .//a[@class="ppContacts_link-site"] # .//a[@class="ppContacts_link-fb"] if self.data.get('show_any_urls') == 'on': try: urls = WebDriverWait(driver, 5).until( lambda driver: driver.find_element_by_xpath(xpah)) urls.click() # ждем откритие окна WebDriverWait(driver, 10).until( EC.number_of_windows_to_be(countswindows)) main_w = driver.window_handles[countswindows - 2] child = driver.window_handles[countswindows - 1] # переключаемся в него driver.switch_to.window(child) # пауза time.sleep( random.randint( int(self.data.get('pause_show_any_urls_min')), int(self.data.get('pause_show_any_urls_max')))) # закрываем и перключаемся назад driver.close() # переходим обратно driver.switch_to.window(main_w) except: self.lg.info('No urls') except: self.lg.exception('show_any_urls')
def extract(self, item, href, key): try: title = item.text self.browser.get(href) sleep(2) self.source = self.getPageText(key) # 拿到网页源码 print(href, title) # self.write_new_file(href, title, self.source, self.i, self.date, key[6]) self.browser.back() return handle = self.browser.current_window_handle # 拿到当前页面的handle item.click() # switch tab window WebDriverWait(self.browser, 10).until(EC.number_of_windows_to_be(2)) handles = self.browser.window_handles for newHandle in handles: if newHandle != handle: self.browser.switch_to.window(newHandle) # 切换到新标签 sleep(2) # 等个几秒钟 self.source = self.getPageText(key) # 拿到网页源码 self.browser.close() # 关闭当前标签页 self.browser.switch_to.window(handle) # 切换到之前的标签页 break print(href, title) # self.write_new_file(href, title, self.source, self.i, self.date, key[6]) except (NoSuchElementException, NoSuchAttributeException) as e: print('Element error:', e) except Exception: return
def switchNewTab(self): driver = webdriver.Firefox() wait = WebDriverWait(driver, 10) driver.get('https://letskodeit.teachable.com/p/practice#top') parentWindow = driver.current_window_handle driver.find_element_by_id("opentab").click() wait.until(ec.number_of_windows_to_be(2)) handles = driver.window_handles print(handles) # time.sleep(3) for window in handles: if window != parentWindow: driver.switch_to.window(window) wait.until( ec.visibility_of_element_located( (By.ID, "search-courses"))) driver.find_element(By.ID, "search-courses").send_keys( "Python", Keys.ENTER) time.sleep(3) break driver.close() driver.switch_to.window(parentWindow) time.sleep(3) driver.find_element_by_id("name").send_keys("Test_Successful") time.sleep(3) driver.close()
def extract(self, item): titleInfo = item.find_element_by_css_selector('a') try: href = titleInfo.get_attribute('href') md5 = crawlerfun.makeMD5(href) # dict filter if md5 in self.d: return else: self.d[md5] = self.date.split(' ')[0] # Insert md5 value into the dict self.i += 1 self.total += 1 title = titleInfo.text handle = self.browser.current_window_handle # Obtain current page handle titleInfo.click() # switch tab window WebDriverWait(self.browser, 10).until(EC.number_of_windows_to_be(2)) handles = self.browser.window_handles for newHandle in handles: if newHandle != handle: self.browser.switch_to.window(newHandle) # Switch new tab sleep(2) # Wait 2 seconds self.source = self.getPageText() # Download page source self.browser.close() # Close current new tab self.browser.switch_to.window(handle) # Switch to before tab break self.write_new_file(href, title, self.source, self.i, self.date, 0000000) except Exception as e: print('Element error:', e)
def click_apply_button(self): self.driver.find_element(*self.APPLY_BUTTON).click() self.wait.until(ec.alert_is_present()) self.driver.switch_to.alert.accept() self.wait.until(ec.number_of_windows_to_be(1)) WindowHelper(self.driver).switch_to_window_by_title(HometaxInquireDataPage.HometaxInquireDataPage.WINDOW_TITLE) return HometaxInquireDataPage.HometaxInquireDataPage(self.driver)
def item_page_shown(self): recently_viewed_items = self.find_elements(*self.RECENTLY_VIEWD_ITEMS) windows_before = self.driver.current_window_handle # Store the parent_window_handle for future use for e in recently_viewed_items: url_link = e.get_attribute("href") self.driver.execute_script( "window.open('" + url_link + "');" ) # Open the hrefs one by one through execute_script method in a new tab WebDriverWait(self.driver, 10).until(EC.number_of_windows_to_be( 2)) # Induce WebDriverWait for the number_of_windows_to_be 2 windows_after = self.driver.window_handles # list for x in windows_after: if x != windows_before: self.driver.switch_to.window(x) # switch_to the new window windows_new = self.driver.current_url assert url_link.find( windows_new ) != -1, f'Expected {url_link} to be in {windows_new}' print(f'Expected url: ' + url_link + f' is in the actual url: ' + windows_new) self.driver.close() # close the window self.driver.switch_to.window( windows_before) # switch_to the parent_window_handle
def click_open_category_page(self): browse_categories = self.find_elements(*self.BROWSE_CATEGORIES) windows_before = self.driver.current_window_handle # Store the parent_window_handle for future use for e in browse_categories: url_link = e.get_attribute("href") #category_title = e.get_attribute("text") print("Perform your verification on page {}".format( self.driver.title)) # print(f'text = ', category_title) self.driver.execute_script( "window.open('" + url_link + "');" ) # Open the hrefs one by one through execute_script method in a new tab WebDriverWait(self.driver, 10).until(EC.number_of_windows_to_be( 2)) # Induce WebDriverWait for the number_of_windows_to_be 2 windows_after = self.driver.window_handles # list for x in windows_after: if x != windows_before: self.driver.switch_to.window(x) # switch_to the new window windows_new = self.driver.current_url assert url_link.find( windows_new ) != -1, f'Expected {url_link} to be in {windows_new}' print(f'Expected url: ' + url_link + f' is in the actual url: ' + windows_new) self.driver.close() # close the window self.driver.switch_to.window( windows_before) # switch_to the parent_window_handle
def twitter_import_contacts(driver): driver.get('https://twitter.com/who_to_follow/import') import_button = WebDriverWait(driver, 2).until( EC.element_to_be_clickable( (By.XPATH, '//*[@id="import-services-list"]/li[1]/button'))) import_button.click() # wait for Gmail oAuth window WebDriverWait(driver, 10).until(EC.new_window_is_opened) driver.switch_to.window(driver.window_handles[1]) time.sleep(2) google_login(driver) allow_button = WebDriverWait(driver, 120).until( EC.element_to_be_clickable((By.ID, 'submit_approve_access'))) allow_button.click() WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(1)) driver.switch_to.window(driver.window_handles[0]) timeline = WebDriverWait(driver, 15).until( EC.visibility_of_element_located((By.ID, 'timeline'))) header = WebDriverWait(driver, 5).until( EC.visibility_of_element_located((By.ID, 'content-main-heading'))) if 'Gmail contacts' in header.text: # print('header located: {}'.format(success_header.text)) return parse_account(driver.page_source) else: return None
def extract(self, item): titleInfo = item.find_element_by_css_selector('h1 > a') try: href = titleInfo.get_attribute('href') md5 = self.makeMD5(href) # dict filter if md5 in self.d: return else: self.d[md5] = self.date.split(' ')[0] # 往dict里插入记录 self.i += 1 title = titleInfo.text handle = self.browser.current_window_handle # 拿到当前页面的handle titleInfo.click() # switch tab window WebDriverWait(self.browser, 10).until(EC.number_of_windows_to_be(2)) handles = self.browser.window_handles for newHandle in handles: if newHandle != handle: self.browser.switch_to.window(newHandle) # 切换到新标签 self.source = self.getPageText() # 拿到网页源码 self.browser.close() # 关闭当前标签页 sleep(2) # 等个几秒钟 self.browser.switch_to.window(handle) # 切换到之前的标签页 break # self.write_new_file(href, title, self.source, self.i, self.date, 1161565) except Exception: self.i -= 1 pass
def logout_except(): count = 0 while True: count += 1 button_order_all.click() time.sleep(1) if not re.match(r'.*disable.*', button_order_all.get_attribute('class')): if count > 10: raise Exception('CAN NOT ORDER !!!') continue else: count = 0 break while True: button_logout.click() try: wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@uifield="okButton"]'))) except selenium.common.exceptions.TimeoutException: if count > 10: raise Exception('CAN NOT click logout_OK !!!') continue else: break button_logout_OK.click() wait_5.until(EC.number_of_windows_to_be(1)) window = driver.window_handles[-1] driver.switch_to_window(window) driver.quit()
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") WebDriverWait(driver, 10) driver.find_element_by_link_text("Add New Country").click() Links = driver.find_elements_by_css_selector("form tbody tr td i") for i in range(len(Links)): print("Переход по ссылке", i + 1) Links[i].click() WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2)) AllOpenWindows = driver.window_handles currentWindow = driver.current_window_handle oldWindow = currentWindow print("текущее окно:", currentWindow) for j in range(len(AllOpenWindows)): if (AllOpenWindows[j] != currentWindow): newWindow = AllOpenWindows[j] print("новое окно:", newWindow) driver.switch_to.window(newWindow) currentWindow = driver.current_window_handle print("перешли в окно:", currentWindow) driver.close() driver.switch_to.window(oldWindow) currentWindow = driver.current_window_handle print("вернулись в старое окно:", currentWindow) driver.quit()
def test_google_plus_link(player_wizard, browser): # noqa """As a player, navbar footer links to google +.""" print('As a player, navbar footer links to google +.') footer = Footer(browser) WebDriverWait(browser, DEFAULT_WAIT_TIME).until( EC.element_to_be_clickable((By.ID, footer.google_plus_id))) app_window = browser.window_handles[0] footer.google_plus.click() WebDriverWait(browser, DEFAULT_WAIT_TIME).until(EC.number_of_windows_to_be(2)) for handle in browser.window_handles: if handle.title() != app_window.title(): browser.switch_to_window(handle) continue WebDriverWait(browser, DEFAULT_WAIT_TIME).until( url_in_new_tab_matches( 'https://plus.google.com/105624626079092258118')) assert browser.current_url.strip( ) == 'https://plus.google.com/105624626079092258118'
def extract(self, info): href = info.get_attribute('href') title = info.text md5 = self.makeMD5(href) # dict filter if md5 in self.d: return else: self.d[md5] = self.date # 往dict里插入记录 self.i += 1 print(href, '====', title) handle = self.browser.current_window_handle # 拿到当前页面的handle info.click() # switch tab window WebDriverWait(self.browser, 10).until(EC.number_of_windows_to_be(2)) handles = self.browser.window_handles for newHandle in handles: if newHandle != handle: self.browser.switch_to.window(newHandle) # 切换到新标签 sleep(1) # 等个几秒钟 self.source = self.getPageText() # 拿到网页源码 self.browser.close() # 关闭当前标签页 self.browser.switch_to.window(handle) # 切换到之前的标签页 break
def test_reddit_link(player_wizard, browser): # noqa """As a player, navbar footer links to reddit.""" print('As a player, navbar footer links to reddit.') footer = Footer(browser) WebDriverWait(browser, DEFAULT_WAIT_TIME).until( EC.element_to_be_clickable((By.ID, footer.reddit_id))) app_window = browser.window_handles[0] footer.reddit.click() WebDriverWait(browser, DEFAULT_WAIT_TIME).until(EC.number_of_windows_to_be(2)) for handle in browser.window_handles: if handle.title() != app_window.title(): browser.switch_to_window(handle) continue WebDriverWait(browser, DEFAULT_WAIT_TIME).until( url_in_new_tab_matches('https://www.reddit.com/r/adventurerscodex/')) assert browser.current_url.strip( ) == 'https://www.reddit.com/r/adventurerscodex/'
def test_ogl_link(player_wizard, browser): # noqa """As a player, navbar footer links to ogl.""" print('As a player, navbar footer links to ogl.') footer = Footer(browser) WebDriverWait(browser, DEFAULT_WAIT_TIME).until( EC.element_to_be_clickable((By.ID, footer.ogl_id))) app_window = browser.window_handles[0] footer.ogl.click() WebDriverWait(browser, DEFAULT_WAIT_TIME).until(EC.number_of_windows_to_be(2)) for handle in browser.window_handles: if handle.title() != app_window.title(): browser.switch_to_window(handle) continue WebDriverWait(browser, DEFAULT_WAIT_TIME).until( url_in_new_tab_matches( 'http://media.wizards.com/2016/downloads/DND/SRD-OGL_V5.1.pdf')) ogl = 'http://media.wizards.com/2016/downloads/DND/SRD-OGL_V5.1.pdf' assert browser.current_url.strip() == ogl
def test_rss_link(player_wizard, browser): # noqa """As a player, navbar footer links to rss.""" print('As a player, navbar footer links to rss.') footer = Footer(browser) WebDriverWait(browser, DEFAULT_WAIT_TIME).until( EC.element_to_be_clickable((By.ID, footer.rss_id))) app_window = browser.window_handles[0] footer.rss.click() WebDriverWait(browser, DEFAULT_WAIT_TIME).until(EC.number_of_windows_to_be(2)) for handle in browser.window_handles: if handle.title() != app_window.title(): browser.switch_to_window(handle) continue # safari does not have an rss reader if browser.name != 'safari': WebDriverWait(browser, DEFAULT_WAIT_TIME).until( url_in_new_tab_matches('https://adventurerscodex.com/feed.xml')) assert browser.current_url.strip( ) == 'https://adventurerscodex.com/feed.xml'
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 wait_number_of_windows_to_be(driver, report): smart_pass = error_occurred_handle(driver, report) if smart_pass: try: element = WebDriverWait(driver, settings.new_window_timeout).until(EC.number_of_windows_to_be(2)) str_ = 'Wait until report view window is open: ' + report + '=pass' common_tools.save_log(str_) except Exception as e: str_ = 'Wait until report view window is open: ' + report + '=Fail: ' + e.__str__() common_tools.save_log(str_) smart_pass = False else: pass return smart_pass
def test_tree_redirect_to_entity_site_page(self): """Test redirect to entity's site page from jsTree context menu.""" self.wait_page_loading() self.open_js_tree_nodes() # open context menu and click at redirect to site's page item_id = self.click_jstree_context_menu_items(1) category_id = Category.objects.get(id=item_id).page.display_h1 # wait new tab opening self.wait.until(EC.number_of_windows_to_be(2)) self.browser.switch_to.window(window_name=self.browser.window_handles[1]) test_h1 = self.wait.until(EC.presence_of_element_located( (By.TAG_NAME, 'h1') )).text self.assertEqual(test_h1, category_id)
def wait_until_tabs_open(self, count_tabs=2, timeout=10): WebDriverWait(self.selenium, timeout).until(EC.number_of_windows_to_be(count_tabs))