def notifications_check(self): wait = self.long_wait long_wait = self.long_wait notification = self.notification wait.until(lambda d: notification.notifications()) self.driver.implicitly_wait(0.5) while True: try: print notification.notifications().get_attribute('class') if 'success' in notification.notifications().get_attribute('class'): wait.until(EC.staleness_of(self.notification.notification('success'))) break elif 'info' in notification.notifications().get_attribute('class'): wait.until(EC.staleness_of(self.notification.notification('info'))) break elif 'progress' in notification.notifications().get_attribute('class'): long_wait.until(EC.staleness_of(self.notification.notification('progress')), message="wysylanie wiadomosci trwalo zbyt dlugo") elif 'warning' in notification.notifications().get_attribute('class'): print 'warning' elif 'error' in notification.notifications().get_attribute('class'): raise Exception('Notification Error') else: continue except StaleElementReferenceException as EX: print EX continue self.driver.implicitly_wait(30)
def wait_for_element_to_reload(self, element_selector): WebDriverWait(self.driver, 20) \ .until(EC.staleness_of(element_selector(self.driver))) WebDriverWait(self.driver, 20) \ .until_not(EC.staleness_of(element_selector(self.driver))) return element_selector(self.driver)
def testExpectedConditionStalenessOf(self, driver, pages): pages.load('dynamicallyModifiedPage.html') element = driver.find_element_by_id('element-to-remove') with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.staleness_of(element)) driver.find_element_by_id('buttonDelete').click() assert 'element' == element.text WebDriverWait(driver, 0.7).until(EC.staleness_of(element)) with pytest.raises(StaleElementReferenceException): element.text
def getSearchResults(searchString): driver.get(url) first_set = True finished = False driver.find_element_by_id("MainContent_rdoByEntityName").click() search_field = driver.find_element_by_id("MainContent_txtEntityName") search_field.send_keys(searchString) driver.find_element_by_id("MainContent_btnSearch").click() try: wait.until( EC.presence_of_element_located((By.ID, "MainContent_UpdatePanelGrid"))) except: print "problem loading results for " + searchString return next_page = 2 #loop through pagesets (separated by ... links) while not finished: #first page of set table = driver.find_element_by_id("MainContent_UpdatePanelGrid") soup = BeautifulSoup(table.get_attribute("innerHTML"), "lxml") f = open('test.txt', 'w') f.write(str(soup)) f.close() processResultsPage(soup) #loop through pages within set while soup.find('a', text=str(next_page)): next_link = driver.find_element_by_link_text(str(next_page)) next_link.click() wait.until(EC.staleness_of(next_link)) table = driver.find_element_by_id("MainContent_UpdatePanelGrid") next_page = next_page + 1 soup = BeautifulSoup(table.get_attribute("innerHTML"), "lxml") processResultsPage(soup) next_links = soup.findAll('a', text="...") #after first 20, only one '...' link if first_set and len(next_links) == 1: next_link = driver.find_element_by_link_text("...") first_set = False elif len(next_links) == 2: next_link = driver.find_elements_by_link_text("...")[1] else: #no continuation links finished = True continue prev_link = driver.find_element_by_link_text(str(next_page - 2)) next_link.click() #instead of waiting for link to phase out, wait for new set of links next_page = next_page + 1 wait.until(EC.staleness_of(prev_link))
def body(self): hamburger = self.driver.find_element_by_css_selector(".readerNavMenuMenuButton") if hamburger: hamburger.click() wait = WebDriverWait(self.driver, TEMPER) wait.until(staleness_of(hamburger)) self.search_for("Dogs") versionedResult = self.driver.find_element_by_css_selector('a[href="/Psalms.59.7/en/The_Rashi_Ketuvim_by_Rabbi_Shraga_Silverstein?qh=Dogs"]') versionedResult.click() WebDriverWait(self.driver, TEMPER).until(staleness_of(versionedResult)) assert "Psalms.59.7/en/The_Rashi_Ketuvim_by_Rabbi_Shraga_Silverstein" in self.driver.current_url, self.driver.current_url
def wait_for_page_reload(self): # Sometimes need to wait for the page reload to complete. First wait for old objects to become stale WebDriverWait(self.driver, Settings.seleniumWaitTime).until( EC.staleness_of(self._theaterMoviesListContainer)) WebDriverWait(self.driver, Settings.seleniumWaitTime).until( EC.staleness_of(self.movies[0])) # Next wait for new objects to become available. NOTE: This is the locator for _theaterMoviesListContainer. WebDriverWait(self.driver, Settings.seleniumWaitTime).until( EC.presence_of_element_located((By.CLASS_NAME, "movies-box"))) # NOTE: this is the locator for movies. WebDriverWait(self.driver, Settings.seleniumWaitTime).until( EC.presence_of_all_elements_located((By.CLASS_NAME, "item")))
def login(username, password): def dict_2_cookiejar(d): cj = CookieJar() for c in d: ck = Cookie( name=c["name"], value=urllib.parse.unquote(c["value"]), domain=c["domain"], path=c["path"], secure=c["secure"], rest={"HttpOnly": c["httponly"]}, version=0, port=None, port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=True, expires=None, discard=True, comment=None, comment_url=None, rfc2109=False, ) cj.set_cookie(ck) return cj if os.path.exists("cookies"): return dict_2_cookiejar(pickle.load(open("cookies", "rb"))) driver = webdriver.PhantomJS(executable_path=config.PHANTOM_JS_PATH) driver.get("http://login.sina.com.cn") user = driver.find_element_by_xpath('//input[@id="username"]') user.send_keys(username) pw = driver.find_element_by_xpath('//input[@id="password"]') pw.send_keys(password) old_page = driver.find_element_by_tag_name("html") driver.find_element_by_xpath('//input[@class="smb_btn"]').click() WebDriverWait(driver, 10).until(staleness_of(old_page)) # TODO change the login url from login.sina.com.cn to weibo.com old_page = driver.find_element_by_tag_name("html") driver.get("http://weibo.com") WebDriverWait(driver, 10).until(staleness_of(old_page)) with open("cookies", "wb") as f: pickle.dump(driver.get_cookies(), f) return dict_2_cookiejar(driver.get_cookies())
def wait_for_loading_staleness(self, style, pseudo_element): """Wait for section load. Parameters: style <str>: element CSS style pseudo <str>: CSS pseudo-element selector '::after' '::before' '::first-letter' '::first-line' '::selection' '::backdrop' '::placeholder' '::marker' '::spelling-error' '::grammar-error' """ pseudo, pseudo_is_valid = self.is_valid_pseudo(pseudo_element) if not pseudo_is_valid: raise ValueError('%s not in %s' % (self.pseudos)) WebDriverWait(self.driver, 90).until( staleness_of( self.driver.find_element( By.CSS_SELECTOR, '%s%s' % (style, pseudo) ) ) )
def close_notifies(selenium, browser_id): driver = selenium[browser_id] notify = driver.find_elements_by_css_selector('.ember-notify ' 'a.close-button, ' '.ember-notify ' '.message') notify = notify[:2] if notify else None while notify: cls_btn, msg = notify try: msg = msg.text cls_btn.click() Wait(driver, WAIT_BACKEND).until( staleness_of(cls_btn), message='waiting for notify "{:s}" to disappear'.format(msg) ) except StaleElementReferenceException: pass notify = driver.find_elements_by_css_selector('.ember-notify ' 'a.close-button, ' '.ember-notify ' '.message') notify = notify[:2] if notify else None
def _buy_offering(self): bought_response_text = read_response_file('responses', 'store2', 'service2_bought.json') self.network._servers['http']['store2.example.com'].add_response('GET', '/mystore/api/offering/offerings/service2.rdf', {'content': bought_response_text}) dialog = FormModalTester(self, self.wait_element_visible(".wc-buy-modal")) dialog.accept() WebDriverWait(self.driver, 10).until(EC.staleness_of(dialog.element)) self.wait_wirecloud_ready()
def switch_to_iframe(self): iframe = self.driver.find_element( *CKEDITORLocators.IFRAME ) self.driver.switch_to.frame(iframe) self.wait_until(staleness_of(iframe))
def wait_for_page_load(self): """Delay progress until the new page is available.""" old_page = self.browser.find_element_by_tag_name('html') yield WebDriverWait(self.browser, self.wait).until( staleness_of(old_page) )
def find_all_questions(self, driver, problems): """Final all available questions.""" questions = {} section = '' wait = WebDriverWait(driver, 5) try: loading = wait.until( expect.visibility_of_element_located( (By.XPATH, '//span[text()="Loading..."]') ) ) wait.until(expect.staleness_of(loading)) except: pass rows = driver.find_elements( By.XPATH, '//div[contains(@class,"exercise-sections")]') for row in rows: children = row.find_elements( By.XPATH, './/div[@class="exercises"]//span[contains(text(),"ID:")]') section = row.find_element( By.XPATH, './label/span[@class="chapter-section"]').text if len(children) == 0: # print('FAQ - No children tags') questions[section] = [] else: questions[section] = [] for q in children: question = q.text.split(' ')[1] questions[section].append(question) return questions
def test_clicking_nav_menu_closes_admin_div_when_clean(self): """ When the admin canvas is "clean" (the user has made no changes), clicking on the left-hand nav menu closes the admin div and renders the clicked view... in this case, the topic view """ self.admin_login_and_open_existing_class_edit() self.open_topic_tree_one_level_with_activities() topic_link = self.browser.find_element_by_xpath( '//ul[@class="nav nav-tabs nav-stacked main-menu"]/li[2]/a[@class="view-tree"]') topic_link.click() admin_div = self.browser.find_element_by_id('admin_div') close_wait = WebDriverWait(self.browser, 3).until( EC.staleness_of(admin_div)) tree_heading = 'Concept Tree - test class, Spring 2012' h2_headers = self.browser.find_elements_by_tag_name('h2') self.assertIn(tree_heading, [header.text for header in h2_headers]) tree = self.browser.find_element_by_id('tree') self.assertTrue(tree.is_displayed()) self.open_topic_tree_one_level_with_activities()
def set_as_top_of_range(self): # FIXME workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1411264 el = self.page.find_element(By.CSS_SELECTOR, 'body') self.find_element(*self._dropdown_toggle_locator).click() self.find_element(*self._set_top_of_range_locator).click() self.wait.until(expected.staleness_of(el)) self.page.wait_for_page_to_load()
def addListItems(driver, fileName): print 'adding courses to list and print to file %s' %fileName cleanFile(fileName) writeFile = open(fileName, 'a') nextText = 'Next' pageNumber = 0 while(nextText == 'Next'): print 'page %d' %pageNumber waitLocated(driver, "(//span/a)[2]") listItems = driver.find_elements_by_xpath("//td[@class='CourseCode']/a") for element in listItems: elementText = element.text print(elementText) writeFile.write(element.text + '\n') nextButton = driver.find_element_by_xpath("(//span/a)[2]") nextText = nextButton.text nextButton.click() WebDriverWait(driver, 10).until( EC.staleness_of(nextButton) ) pageNumber+=1 writeFile.close()
def click_share_btn(self): self.click_element(CreateIdeaPageLocators.SHARE_BTN) self.wait_until( visibility_of_element_located(IdeaPageLocators.IDEA_TITLE), ) self.wait_for_flash_message_to_dissapear() assert staleness_of(IdeaPageLocators.SHARE_ERROR)
def __exit__(self, type, value, tb): if type: pass else: self.portal.switch_to_default_content() if self.portal.getRepoVersion() >= 10584: # wait for interaction to be detached from DOM, to avoid # subsequent waits for interaction pages from finding # this interaction. self.portal.wait(self.timeout, *self.args, **self.kw).until( expected_conditions.staleness_of(self.iframe) ) else: # Older versions of the portal fail to detach the # interaction page properly, leading to multiple # interactions in the DOM (although they are hidden). # These portals can be made to work by deleting the # instances of id 'modal-interaction-dialog' that are # children of the body. self.portal.wait(60).until( expected_conditions.presence_of_element_located( (By.XPATH, '/html/body/div[@id="modal-interaction-dialog"]') ) ) self.portal.execute_script('document.getElementById("body").removeChild(document.getElementById("modal-interaction-dialog"))')
def _wait_until_page_ready(self, timeout=None): """Semi blocking API that incorporated different strategies for cross-browser support.""" if self._block_until_page_ready: delay = self._browser_breath_delay if delay < 1: delay *= 10 # let the browser take a deep breath... sleep(delay) timeout = self._implicit_wait_in_secs \ if timeout is None else utils.timestr_to_secs(timeout) browser = self._current_browser() try: WebDriverWait(None, timeout, self._poll_frequency).\ until_not(staleness_of(browser.find_element_by_tag_name('html')), '') except: # instead of halting the process because document is not ready # in <TIMEOUT>, we try our luck... self._debug(exc_info()[0]) try: WebDriverWait(browser, timeout, self._poll_frequency).\ until(lambda driver: driver. execute_async_script(self._page_ready_bootstrap), '') except: # instead of halting the process because document is not ready # in <TIMEOUT>, we try our luck... self._debug(exc_info()[0]) for keyword in self._page_ready_keyword_list: self._builtin.run_keyword(keyword)
def extract_index_urls(): browser = Browser() # Search for metrics browser.get('http://www.epaveldas.lt/patikslintoji-paieska') browser.find_element_by_class_name('inputParam').send_keys('RKB metrikų knyga') browser.find_element_by_class_name('btn2Parts').click() browser.wait_element_by_class_name('objectsDataTable') # Change number of results in page to be 50 browser.find_element_by_xpath('//select[contains(@id, "SlctPageSize")]/option[@value="50"]').click() browser.wait_n_elemens_by_css_selector(50, '.wInfo .searchResultDescription a') # Collect all search result links next_btn = browser.find_element_by_xpath('//img[@title="Sekantis psl."]/..') next_btn_style = next_btn.get_attribute('style') while 'cursor:default' not in next_btn_style: for link in browser.find_elements_by_css_selector('.wInfo .searchResultDescription a'): yield link.get_attribute('href'), link.text next_btn.click() try: browser.wait.until(ec.staleness_of(link)) except TimeoutException: break next_btn = browser.find_element_by_xpath('//img[@title="Sekantis psl."]/..') next_btn_style = next_btn.get_attribute('style') browser.quit()
def browser_login_user(self, username, password, facility_name=None, browser=None): """ Tests that an existing admin user can log in. """ browser = browser or self.browser login_url = self.reverse("login") self.browse_to(login_url, browser=browser) # Load page # Focus should be on username, password and submit # should be accessible through keyboard only. if facility_name and browser.find_element_by_id("id_facility").is_displayed(): self.browser_activate_element(id="id_facility") self.browser_send_keys(facility_name) username_field = browser.find_element_by_id("id_username") username_field.clear() # clear any data username_field.click() # explicitly set the focus, to start self.browser_form_fill(username, browser=browser) self.browser_form_fill(password, browser=browser) username_field.submit() # self.browser_send_keys(Keys.RETURN) # wait for 5 seconds for the page to refresh WebDriverWait(browser, 5).until(EC.staleness_of(username_field))
def _get_user_cookies(self): url = target_url + login_page_path self.driver.get(url) try: user_input = self.driver.find_element_by_name('mail') passwd_input = self.driver.find_element_by_name('password') submit_btn = self.driver.find_element_by_class_name('pr20') except NoSuchElementException: raise PageHtmlChanged( "%s login page structure have changed!" % _domain) user_input.send_keys(self.username) passwd_input.send_keys(self.passwd) submit_btn.click() try: WebDriverWait(self.driver, 3).until(staleness_of(submit_btn)) except TimeoutException: raise Exception("Wrong username or password!") WebDriverWait(self.driver, timeout=10).until(has_page_load) try_times = 0 while True: time.sleep(1) if url != self.driver.current_url: return self.driver.get_cookies() try_times += 1 if try_times > 10: raise Exception("Getting cookie info failed!")
def context_to_assert_page_reload(self, time_out=1): old_page = self.find_element_by_tag_name('html') yield wait = WebDriverWait(self, time_out) wait.until( EC.staleness_of(old_page) )
def sort_by(self, category): el = self.selenium.find_element(*SearchResultList._results_locator) super(Sorter, self).sort_by(category) WebDriverWait(self.selenium, self.timeout).until(expected.staleness_of(el)) WebDriverWait(self.selenium, self.timeout).until( expected.visibility_of_element_located( SearchResultList._results_locator))
def test_user_can_create_event(app): wd = app.wd app.session.login_as(app.users["user2"]) app.open_page("events") wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[.='Создать событие']")).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[@class='select2-chosen']")).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Кастинг']")).click() event_name = "Тест создания" + strftime("%H:%M:%S", gmtime()) # делаем имя уникальным для возможности повторного запуска wd.find_element_by_id("Event_title").send_keys(event_name) image_file = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../images/event_logo.jpg")) wd.find_element_by_name("image").send_keys(image_file) wait(wd, 60).until(lambda s: wd.find_element_by_id("button_crop_recortar")).click() crop_button = wait(wd, 60).until(ec.element_to_be_clickable((By.ID, "button_crop_original"))) time.sleep(5) crop_button.click() wait(wd, 60).until(ec.staleness_of(crop_button)) current_date = strftime("%m/%d/%Y", gmtime()) #переделать на генерацию будущих дат wait(wd, 10).until(lambda s: wd.find_element_by_id("Event_start_date")).send_keys(current_date) wait(wd, 10).until(lambda s: wd.find_element_by_id("Event_end_date")).send_keys(current_date) wait(wd, 10).until(lambda s: wd.find_element_by_id("town_id")).send_keys("Москва") wait(wd, 10).until(lambda s: wd.find_element_by_id("Event_address")).send_keys("Адрес события, 123") editor = wait(wd, 60).until(lambda s: wd.find_element_by_css_selector("iframe.cke_wysiwyg_frame")) wd.switch_to_frame(editor) wait(wd, 60).until(lambda s: wd.find_element_by_css_selector("body")).send_keys("Sample description") wd.switch_to_default_content() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//input[@class='btn btn_green']")).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1")) assert wd.find_element_by_xpath("//h1").text == event_name #можно добавить удаление в админке
def _navigate(self, locator): el = self.selenium.find_element(*SearchResultList._results_locator) self.selenium.find_element(*locator).click() WebDriverWait(self.selenium, self.timeout).until(expected.staleness_of(el)) WebDriverWait(self.selenium, self.timeout).until( expected.visibility_of_element_located( SearchResultList._results_locator))
def get_next_page(self, link_text): u""" 目的: 引数で与えられたリンクをクリックする 引数: * link_text - リンクのテキスト 戻り値: * TrueかFalseを返す """ try: # next button '次のページ'をクリックする old_page = (self.driver.find_element_by_tag_name('html')) self.driver.find_element_by_link_text(link_text).click() WebDriverWait(self.driver, 30).until( EC.staleness_of(old_page)) except NoSuchElementException as error_code: logprint('NoSuchElementException') logprint(error_code) return False except StaleElementReferenceException as error_code: logprint('StaleElementReferenceException') logprint(error_code) return False except TimeoutException as error_code: logprint('TimeoutException') logprint(error_code) return False except WebDriverException as error_code: logprint('WebDriverException') logprint(error_code) return False else: return True
def select_mozilla_central_repo(self): self.open_repos_menu() # FIXME workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1411264 el = self.find_element(By.CSS_SELECTOR, 'body') self.find_element(*self._mozilla_central_repo_locator).click() self.wait.until(EC.staleness_of(el)) self.wait_for_page_to_load()
def testExpectedConditionStalenessOf(self): self._loadPage('dynamicallyModifiedPage') element = self.driver.find_element_by_id('element-to-remove') try: WebDriverWait(self.driver, 0.7).until(EC.staleness_of(element)) self.fail("Expected TimeoutException to have been thrown") except TimeoutException as e: pass self.driver.find_element_by_id('buttonDelete').click() self.assertEqual('element', element.text) WebDriverWait(self.driver, 0.7).until(EC.staleness_of(element)) try: element.text self.fail("Expected StaleReferenceException to have been thrown") except StaleElementReferenceException as e: pass
def register(self, form_data): """ Fill in the registration form and click the submit button, if the form is valid. """ self.client.get('{host}{path}'.format( host=self.live_server_url, path=reverse('beta:register'), )) for field, value in form_data.items(): element = self.form.find_element_by_name(field) if (element.get_attribute('type') == 'checkbox' and bool(value) != element.is_selected()): element.click() else: element.send_keys(value) # Wait for ajax validation to complete time.sleep(1) # If the form is valid, click the submit button and wait for the next # page to load if self.form_valid(): submit = self.form.find_element_by_tag_name('button') html = self.client.find_element_by_tag_name('html') submit.click() WebDriverWait(self.client, timeout=3) \ .until(expected_conditions.staleness_of(html)) return self.client.page_source
def wait_for_stale_element(self, element: "WebElement", timeout: int = _DEFAULT_TIMEOUT) -> None: """ Espera a que un elemento desaparezca del DOM Args: element (WebElement): un WebElement de webdriver que representa el elemento. NO es un Locator timeout: cantidad máxima de tiempo a esperar antes de lanzar una excepción Returns: None """ self.get_wait(timeout).until( ec.staleness_of(element), message= "Esperaba que el elemento desapareciera del DODM pero no lo hizo")
def test_changeform_does_reload_and_unlock_for_user(self): """Clicking the 'remove lock' button should take over the lock""" other_user, _ = user_factory(model=BlogArticle) Lock.objects.force_lock_object_for_user(self.blog_article, other_user) self._login('admin:locking_blogarticle_change', self.blog_article.pk) self._wait_for_el('#locking-take-lock') self.assert_no_js_errors() body_el = self.browser.find_element_by_tag_name('body') self.browser.find_element_by_id('locking-take-lock').click() # ensure the page has reloaded WebDriverWait(self.browser, 10).until(staleness_of(body_el)) self._wait_until_page_loaded() lock = Lock.objects.for_object(self.blog_article)[0] self.assertEqual(lock.locked_by.pk, self.user.pk)
def step_impl(context): new_browser_window = context.browser.find_element_by_id("button1") print("Before refresh" + new_browser_window.text) context.browser.refresh() try: WebDriverWait(context.browser, 3).until(EC.staleness_of(new_browser_window)) print( "After refresh if we reached here means new browser window WebElement is stale now" ) except (TimeoutException): print( "After refresh if we reached here means timeout exception occured, thet means element is NOT stale" ) # traceback.print_exc() finally: print("Continue execution in the finally block")
def test_register_unmatching_passwords(self): driver = self.driver driver.get("http://127.0.0.1:8000/shop_site/register/") username = driver.find_element_by_id("id_username") password1 = driver.find_element_by_id("id_password1") password2 = driver.find_element_by_id("id_password2") confirm = driver.find_element_by_class_name("btn-primary") username.clear() password1.clear() password2.clear() username.send_keys("newuser") password1.send_keys("unusual") password2.send_keys("unusualgsdfsdfsdf") old_page = driver.find_element_by_tag_name('html') confirm.click() WebDriverWait(driver, 20).until(EC.staleness_of(old_page)) assert "The two password fields didn't match." in driver.page_source
def wait_for_page_load(driver, timeout=10): # I used chrome to get this xpath check_ele = driver.find_element_by_xpath( '//*[@id="center"]/div[2]/div[2]/div[2]/div') check_text = check_ele.text if check_text == u'暂无数据': old_td = None else: old_td = driver.find_element_by_xpath( '//*[@id="center"]/div[2]/div[2]/div[2]/div[1]/table/tbody/tr[1]/td[2]' ) yield # yield nothing, just want keep the current state of old_td # when exit the with wait_for_page_load block, the next line # make sure that the old_td will be changed, or 'no next page' element showing up if old_td: WebDriverWait(driver, timeout=timeout).until(EC.staleness_of(old_td))
def test_7(driver): wait = WebDriverWait(driver, 4) driver.get('http://localhost/litecart') cart_locator = 'div#cart span.quantity' sizes = ('Small', 'Medium', 'Large') quantities = (1, 2, 3, 4, 5) for i in range(5): prev_cart_items = int( driver.find_element_by_css_selector(cart_locator).text) driver.find_element_by_css_selector( 'div#box-campaign-products div[data-id="1"]').click() Select( driver.find_element_by_css_selector( 'select[name="options[Size]"]')).select_by_value( random.choice(sizes)) driver.find_element_by_css_selector('input[name=quantity]').clear() quantity = random.choice(quantities) driver.find_element_by_css_selector('input[name=quantity]').send_keys( str(quantity)) driver.find_element_by_css_selector( 'button[name=add_cart_product]').click() driver.find_element_by_css_selector('div[aria-label=Close]').click() wait.until( ec.text_to_be_present_in_element((By.CSS_SELECTOR, cart_locator), str(prev_cart_items + quantity))) new_cart_items = int( driver.find_element_by_css_selector(cart_locator).text) assert new_cart_items - prev_cart_items == quantity driver.find_element_by_css_selector('div#cart').click() items = len(driver.find_elements_by_css_selector('table tr.item')) for i in range(items): table = driver.find_element_by_css_selector( 'table[class*="items table"]') remove_buttons = driver.find_elements_by_css_selector( 'tr.item button[name=remove_cart_item]') assert len(remove_buttons) > 0 remove_buttons[0].click() wait.until(ec.staleness_of(table)) driver.find_element_by_css_selector('p a[href]').click() assert int(driver.find_element_by_css_selector(cart_locator).text) == 0
def __get_pdf_from_html(driver_path: str, path: str, timeout: int, install_driver: bool, print_options={}): webdriver_options = Options() webdriver_prefs = {} driver = None webdriver_options.add_argument('--headless') webdriver_options.add_argument('--disable-gpu') webdriver_options.add_argument('--no-sandbox') webdriver_options.add_argument('--disable-dev-shm-usage') webdriver_options.experimental_options['prefs'] = webdriver_prefs webdriver_prefs['profile.default_content_settings'] = {'images': 2} if install_driver: download_path = ChromeDriverManager(path='bin').install() binary = manager_path_binary(download_path) driver = webdriver.Chrome(binary, options=webdriver_options) else: try: driver = webdriver.Chrome(driver_path, options=webdriver_options) except: download_path = ChromeDriverManager(path='bin').install() binary = manager_path_binary(download_path) driver = webdriver.Chrome(binary, options=webdriver_options) driver.get(path) try: WebDriverWait(driver, timeout).until( staleness_of(driver.find_element_by_tag_name('html'))) except TimeoutException: calculated_print_options = { 'landscape': False, 'displayHeaderFooter': False, 'printBackground': True, 'preferCSSPageSize': True, } calculated_print_options.update(print_options) result = __send_devtools(driver, "Page.printToPDF", calculated_print_options) driver.quit() return base64.b64decode(result['data'])
def get_filtering_products_by_price(self): wd = self.app.wd wd.get(f"http://{self.app.domain}/acme-corp-m-1/") wd.find_element_by_xpath("//span[.='Price']").click() prices = [] while True: list_prices_obj = wd.find_elements_by_xpath( "//span[@class='price']") for i in list_prices_obj: prices.append(int(re.sub('\D', '', i.text))) try: wd.find_element_by_xpath("//a[.='Next']").click() wait = WebDriverWait(wd, 5) wait.until(EC.staleness_of(list_prices_obj[0])) except: break return prices
def MakeRegisterOrLogIn(self): driver = self.driver # user EMAIL AND PASSWORD FROM .env file Email = os.environ.get("EMAIL") Password = os.environ.get("PASSWORD") # click loginOrRegisterButton time.sleep(4) elm = driver.find_element( By.XPATH, "/html/body/div[1]/div[1]/header/nav/div/div[2]/ul/li[5]/a") elm.click() # fill Email Input time.sleep(4) emailInput = driver.find_element( By.XPATH, "/html/body/div[1]/div[2]/div/div[2]/div[3]/div[1]/form/div[1]/input" ) emailInput.clear() emailInput.send_keys(Email) # fill password Input time.sleep(4) passwordInput = driver.find_element( By.XPATH, "/html/body/div[1]/div[2]/div/div[2]/div[3]/div[1]/form/div[2]/div/input" ) passwordInput.clear() passwordInput.send_keys(Password) # captha Validation Manual print("Please fill the captha manually") WaitUntillUserNotClickToLoginButton = driver.find_element( By.XPATH, "/html/body/div[1]/div[2]/div/div[2]/div[3]/div[1]/form/div[3]/div[3]/button" ) WebDriverWait(driver, timeout=500).until( EC.staleness_of(WaitUntillUserNotClickToLoginButton)) time.sleep(4) self.runProcessInfiniteTimes()
def test_add_cart(driver): driver.get("http://localhost/litecart") while True: driver.find_element_by_css_selector("div.content a.link").click() items_counter = driver.find_element_by_css_selector( "div#cart .quantity") ic_next_text = int(items_counter.text) + 1 call_def = is_element_present( driver, By.CSS_SELECTOR, "select[name='options[Size]']") # element Select if call_def == True: Select( driver.find_element_by_css_selector( "select[name='options[Size]']")).select_by_value("Small") driver.find_element_by_css_selector( "button[name=add_cart_product]").click() WebDriverWait(driver, 10).until( EC.text_to_be_present_in_element( (By.CSS_SELECTOR, "div#cart span.quantity"), str(ic_next_text))) if int(driver.find_element_by_css_selector( "div#cart .quantity").text) < 3: driver.find_element_by_css_selector("li.general-0 a").click() else: driver.find_element_by_css_selector("div#cart a.link").click() break driver.implicitly_wait(10) small_icons = driver.find_elements_by_css_selector("a.inact") if len(small_icons) > 0: small_icons[0].click() buttons_r = driver.find_elements_by_css_selector( "button[name = remove_cart_item]") while len(buttons_r) > 0: goods_table = driver.find_element_by_css_selector( "table.dataTable.rounded-corners") buttons_r[0].click() WebDriverWait(driver, 10).until(EC.staleness_of(goods_table)) buttons_r = driver.find_elements_by_css_selector( "button[name = remove_cart_item]")
def explicit_wait(browser, track, ec_params, timeout=35, notify=True): if not isinstance(ec_params, list): ec_params = [ec_params] # find condition according to the tracks if track == "VOEL": elem_address, find_method = ec_params ec_name = "visibility of element located" find_by = (By.XPATH if find_method == "XPath" else By.CSS_SELECTOR if find_method == "CSS" else By.CLASS_NAME) locator = (find_by, elem_address) condition = EC.visibility_of_element_located(locator) elif track == "TC": expect_in_title = ec_params[0] ec_name = "title contains '{}' string".format(expect_in_title) condition = EC.title_contains(expect_in_title) elif track == "PFL": ec_name = "page fully loaded" def condition(browser): return browser.execute_script("return document.readyState") in [ "complete" or "loaded" ] elif track == "SO": ec_name = "staleness of" element = ec_params[0] condition = EC.staleness_of(element) # generic wait block try: wait = WebDriverWait(browser, timeout) result = wait.until(condition) except: if notify is True: print( "Timed out with failure while explicitly waiting until {}!\n". format(ec_name)) return False return result
def click_on_spa_and_wellness_centre(self, test_data): try: if test_data: if self.driver.find_element_by_xpath(self.spa_and_wellness_centre_xpath).is_displayed(): spa_and_wellness_centre_element = self.driver.find_element_by_xpath( self.spa_and_wellness_centre_xpath) spa_and_wellness_centre_element.click() search_message_element = WebDriverWait(self.driver, 20).until( expected_conditions.presence_of_element_located((By.XPATH, self.search_message_xpath))) WebDriverWait(self.driver, 20).until( expected_conditions.staleness_of(search_message_element)) except NoSuchElementException: print("Could not find element with the locator provided.") except ElementNotVisibleException: print("Element with the locator provided is not visible.") except ElementClickInterceptedException: print("Element with locator provided could not be clicked.")
def staleness_of(self, element, driver=None, timeout=30): ''' Wait until an element is no longer attached to the DOM. element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise. ''' driver = driver or self.driver try: element = WebDriverWait(driver, timeout).until( EC.staleness_of(element)) return element except Exception as e: # print("wait_for_element timeout: ") print(str(e)) return None
def login(self, username: str, password: str): self.driver.get("https://platform.gisaid.org/epi3/frontend") time.sleep(5) login = self.driver.find_element_by_name("login") login.send_keys(username) passwd = self.driver.find_element_by_name("password") passwd.send_keys(password) login_box = self.driver.find_element_by_class_name( "form_button_submit") self.driver.execute_script( "document.getElementById('sys_curtain').remove()") self.driver.execute_script( "document.getElementsByClassName('form_button_submit')[0].click()" ) WebDriverWait(self.driver, 30).until(cond.staleness_of(login_box))
def check_nested_link(main_page: MainPage, parent_locator, nested_locator, error_msg=''): html = main_page.find((By.TAG_NAME, 'html')) driver = main_page.driver try: ActionChains(driver) \ .move_to_element(driver.find_element(parent_locator)) \ .pause(1) \ .click(driver.find_element(nested_locator)) \ .perform() main_page.wait(main_page.load_time).until( conditions.staleness_of(html)) except WebDriverException as err: raise AssertionError(error_msg) from err assert main_page.check_url_negative()
def test3(self): """ 3. Use google to enter "bourbon" in the search field. Then find and click the "I'm Feeling Lucky" link for one of the auto-complete suggestions. """ driver = self.driver driver.get("http://www.google.ca") self.assertIn("Google", driver.title) elem_query = driver.find_element_by_name("q") elem_query.send_keys('bourbon') elem_query.click() # set focus so that Keys.DOWN works elem_query.send_keys(Keys.DOWN*2) elem_ifl = driver.find_element_by_partial_link_text("I'm Feeling Lucky") elem_ifl.click() self.wait.until(EC.staleness_of(elem_ifl)) self.assertNotIn('Google', driver.title)
def _wait_until_html_ready(self, browser, timeout): """Wait until HTML is ready by using stale check.""" # pylint: disable=no-member delay = self._inputs['browser_breath_delay'] if delay < 1: delay *= 10 # let the browser take a deep breath... sleep(delay) try: # pylint: disable=no-member WebDriverWait(None, timeout, self._inputs['poll_frequency']).\ until_not(staleness_of(browser.find_element_by_tag_name('html')), '') except: # instead of halting the process because document is not ready # in <TIMEOUT>, we try our luck... # pylint: disable=no-member self._debug(exc_info()[0])
def get_calendar(self, refresh_button: WebElement = None) -> WebElement: try: old_calendar = self.browser.find_element_by_xpath(self.CALENDAR_XPATH) if refresh_button: self.click_elem(refresh_button) self.wait.until(EC.staleness_of(old_calendar)) return self.browser.find_element_by_xpath(self.CALENDAR_XPATH) else: return old_calendar except NoSuchElementException: try: self.browser.find_element_by_id(self.SPACE_NOT_FOUND_ERR_ID) return None except NoSuchElementException: pass self.wait.until(EC.presence_of_element_located((By.XPATH, self.CALENDAR_XPATH))) return self.browser.find_element_by_xpath(self.CALENDAR_XPATH)
def wait_for_element_not_present(self, element, timeout): """Wait for element not present in the DOM :Args: - element: an element tuple, a CSS string or a WebElement object - timeout: time to wait (in seconds) """ found_element = None try: found_element = self.find(element, timeout=0) except ElementNotFound: pass if found_element: wait = WebDriverWait(self, timeout) message = ('Timeout waiting for element {} to not be present' .format(found_element.name)) wait.until(ec.staleness_of(found_element), message=message)
def navigate_waypoint(self, driver, waypoint, timeout): log.info('Navigating ' + str(waypoint)) elem = get_element(driver, waypoint.locator, timeout=timeout) jitter(.4) elem.click() try: WebDriverWait(driver, timeout).until( EC.staleness_of(elem) ) except TimeoutException: pass if remove_qs(driver.current_url) == BASE_URL + waypoint.dest: log.info("Navigated to '{}'".format(waypoint.dest)) else: raise NavigationException( "Navigation to '{}' failed".format(waypoint.dest) )
def main(): driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) # seconds try: for _ in range(3): driver.get("http://localhost/litecart/en/") wait.until(EC.title_contains("My Store")) link = driver.find_element_by_css_selector( ".content .product a") # ссылка на первую утку link.click() wait.until(EC.title_contains("My Store")) q = driver.find_element_by_css_selector( "#cart span.quantity") # количество уток в корзине quantity = int(q.text) elm = driver.find_elements_by_name( "options[Size]") # селект у желтой утки if len(elm) > 0: select = Select(elm[0]) select.select_by_index(1) # установили размер утки - маленькая btn = driver.find_element_by_name( "add_cart_product") # кнопка Добавить в корзину btn.click() wait.until( EC.text_to_be_present_in_element( (By.CSS_SELECTOR, "#cart span.quantity"), str(quantity + 1))) # количество уток увеличилось print("Товары добавлены успешно") link = driver.find_element_by_css_selector( "#cart a.link") # ссылка на корзину link.click() wait.until(EC.title_contains("My Store")) # в корзине buttons = driver.find_elements_by_name("remove_cart_item") for _ in range(len(buttons)): button = driver.find_element_by_name( "remove_cart_item") # кнопка Удалить товар из корзины table = driver.find_element_by_css_selector( ".dataTable") # таблица заказа wait.until(EC.visibility_of(button)) button.click() wait.until(EC.staleness_of(table)) print("Товары удалены успешно") finally: driver.close()
def skip_intro_js(self): """ Skipping intro_js is a tricky business, as it only appears the first time through one of the demos... which is why we have this try/except pattern here. """ wait = WebDriverWait(self.driver, 2) try: el = wait.until( EC.element_to_be_clickable( (By.CLASS_NAME, 'introjs-skipbutton'))) except TimeoutException: # introjs already ran on a different demo, so it won't show up return el.click() overlay = self.driver.find_element_by_class_name('introjs-overlay') wait.until(EC.staleness_of(overlay))
def travelPages(driver): '''travels all the available listing pages one by one.''' try: i = 0 while True: try: nextpageBtn = driver.find_element_by_xpath( '//a[@title="Sonraki"]') #NoSuchElementException except NoSuchElementException: nextpageBtn = None except Exception: print("yeah reall kill yourself") nextpageBtn = None except BaseException: print("suicide") nextpageBtn = None listings = driver.find_elements_by_xpath( '//*[@id="searchResultsTable"]/tbody/tr[@data-id]') random.shuffle(listings) for j, e in enumerate(listings): ActionChains(driver).move_to_element( e).perform() #eski hoveron link = e.find_element_by_tag_name("a").get_attribute("href") print(link) #TIKLANMIŞ LİNK KONTROL #listingId=link.split("-")[len(link.split("-"))-1].split("/")[0] #if frbs.isExists(listingId): continue #checkIfExists(driver) oldHandle = driver.current_window_handle driver.execute_script("window.open('" + link + "');") driver.switch_to.window(driver.window_handles[1]) scrapeListing(driver) driver.close() driver.switch_to.window(oldHandle) ##???? gerekli mi if j >= listingsToScrapePerPage: break i = i + 1 if nextpageBtn is None or i > pagesToScrape: return driver.execute_script("arguments[0].click();", nextpageBtn) WebDriverWait(driver, 10).until(EC.staleness_of(nextpageBtn)) except Exception as ex: print("amanın. kritik hata.", str(ex)) FileIO.dosyayaYaz("hata.txt", Firebase.getTime() + str(ex) + "\n")
def __get_pdf_from_html(path: str, timeout: int, install_driver: bool, print_options={}): webdriver_options = Options() webdriver_prefs = {} driver = None webdriver_options.add_argument('--headless') webdriver_options.add_argument('--disable-gpu') webdriver_options.add_argument('--no-sandbox') webdriver_options.add_argument('--disable-dev-shm-usage') webdriver_options.experimental_options['prefs'] = webdriver_prefs webdriver_prefs['profile.default_content_settings'] = {'images': 2} # 使用指定的chromedriver if settings.CHROMIUM_DRIVER_PATH is not None: driver = webdriver.Chrome(executable_path=settings.CHROMIUM_DRIVER_PATH,options=webdriver_options) # 使用默认的chromedriver else: if install_driver: driver = webdriver.Chrome( ChromeDriverManager( url='https://npm.taobao.org/mirrors/chromedriver/', latest_release_url='https://npm.taobao.org/mirrors/chromedriver/LATEST_RELEASE', chrome_type=ChromeType.GOOGLE if settings.CHROMIUM_DRIVER == 'Chrome' else ChromeType.CHROMIUM ).install(), options=webdriver_options ) else: driver = webdriver.Chrome(options=webdriver_options) driver.get(path) try: WebDriverWait(driver, timeout).until(staleness_of(driver.find_element_by_tag_name('html'))) except TimeoutException: calculated_print_options = { 'landscape': False, 'displayHeaderFooter': False, 'printBackground': True, 'preferCSSPageSize': True, } calculated_print_options.update(print_options) result = __send_devtools(driver, "Page.printToPDF", calculated_print_options) driver.quit() return base64.b64decode(result['data'])
def upload_files(self, files, timeout=None): # Открыть панель "Загрузка файлов" WebDriverWait(self.driver, explicit_wait).until(EC.element_to_be_clickable((By.ID, 'titleDataUploadAndSave'))).click() # Заполнить таблицу файлами WebDriverWait(self.driver, explicit_wait).until(EC.presence_of_element_located((By.ID, 'file'))).send_keys(files) # Подождать, пока пропадет спиннер try: spinner = WebDriverWait(self.driver, explicit_wait).until(EC.visibility_of_element_located((By.CLASS_NAME, 'w2ui-lock-msg'))) # По умолчанию ждать завершения загрузки длительное время spinner_timeout = timeout if spinner_timeout is None: spinner_timeout = explicit_wait_for_upload WebDriverWait(self.driver, spinner_timeout).until(EC.staleness_of(spinner)) except: print('Spinner was not handled')
def select_block_option(self, value): ''' Select Block value from dropdown. Wait until GP value has loaded before returning. ''' path = '//select[@id="ddlGP"]' WebDriverWait(self.driver, 20).until( EC.presence_of_element_located((By.ID, 'ddlGP'))) gp_select_elem = self.driver.find_element_by_xpath(path) block_select = self.get_block_select() block_select.select_by_value(value) WebDriverWait(self.driver, 20).until(EC.staleness_of(gp_select_elem)) return self.get_block_select()
def remove_one_duck_v2(self, value): wd = self.app.wd wait = self.wait # ввести новое значение # wd.find_element_by_css_selector('input[name="quantity"]').click() wd.find_element_by_css_selector('input[name="quantity"]').clear() wd.find_element_by_css_selector('input[name="quantity"]').send_keys('%s' % value) # первый элемент который пропадет после обновления # element = wd.find_element_by_css_selector( 'tr:not([class="header"]):not([class="footer"]) td[style="text-align: center;"]') # обновить значение # wd.find_element_by_css_selector('button[name="update_cart_item"]').click() # ожидание изменения таблицы # try: wait.until(EC.staleness_of(element)) print('Количество уток поубавилось') except Exception as txt: print('Одноцветные утки кончились, или исключение =', txt)
def test_login_logout(self): driver = self.driver driver.get("http://127.0.0.1:8000/shop_site/accounts/login/") username = driver.find_element_by_id("id_username") password = driver.find_element_by_id("id_password") username.clear() username.send_keys("patchy") password.clear() password.send_keys("nopasaran") password.send_keys(Keys.RETURN) try: login = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, "merch_list"))) finally: logout = driver.find_element_by_link_text("Logout") old_page = driver.find_element_by_tag_name('html') logout.click() WebDriverWait(driver, 20).until(EC.staleness_of(old_page)) assert "Welcome, new user" in driver.page_source
def assertinvisibility(self, xpath): '''断言元素消失,如元素被删除''' try: ele = self.driver.find_elements_by_xpath(xpath) if len(ele) == 0: self.writer.write(self.writer.row, 7, 'PASS') return True # 移除的概念不好理解啊 elif (WebDriverWait(self.driver, 10, 0.5).until( EC.staleness_of( self.driver.find_element_by_xpath(xpath)))): self.writer.write(self.writer.row, 7, 'PASS') return True except Exception as e: logger.error(traceback.format_exc()) self.writer.write(self.writer.row, 7, 'FAIL') self.writer.write(self.writer.row, 8, str(e)) return False
def wait_till_element_is_not_attached_to_dom(self, web_element, timeout=10): """ Wait until an element is no longer attached to the DOM. element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise. """ wait = WebDriverWait( self._driver, timeout=int(timeout), ignored_exceptions=(StaleElementReferenceException, NoSuchElementException)) try: wait.until(EC.staleness_of(web_element)) return True except TimeoutException: return False