def testExpectedConditionInvisiblityOfElement(driver, pages): pages.load("javascriptPage.html") target = driver.find_element_by_id('clickToHide') driver.execute_script("delayedShowHide(0, true)") with pytest.raises(TimeoutException): WebDriverWait(driver, 0.7).until(EC.invisibility_of_element(target)) driver.execute_script("delayedShowHide(200, false)") element = WebDriverWait(driver, 0.7).until(EC.invisibility_of_element(target)) assert element.is_displayed() is False assert target == element
def dismiss_tips(self): wait = WebDriverWait(self.driver, self.timeout) wait.until( EC.invisibility_of_element( (By.XPATH, '//*[@id="game-wrapper"]/div[1]'))) element = wait.until( EC.element_to_be_clickable((By.XPATH, self._canvas_xpath))) element.click()
def isLoadingAnimationDisappear(self): wait = WebDriverWait(self.driver, 10) loadingAnimation = self.driver.find_element_by_xpath(f"//div[contains(@class, 'MuiBackdrop-root')]") try: wait.until(EC.invisibility_of_element(loadingAnimation)) return True except TimeoutException: return False
def get_bovada(): driver.get("https://www.bovada.lv/sports/soccer") WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.CLASS_NAME, 'next-events-bucket'))) # change odds format dropdown = driver.find_element_by_class_name( "sp-odds-format-selector-filter") dropdown.click() WebDriverWait(dropdown, 5).until( EC.invisibility_of_element((By.LINK_TEXT, ' Decimal Odds '))) decimal_odds = dropdown.find_element_by_xpath( "//li[text()=' Decimal Odds ']") decimal_odds.click() show_more_btn = driver.find_element_by_id("showMore") show_more_btn.click() WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.CLASS_NAME, 'next-events-bucket'))) WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, 'showLess'))) div = driver.find_element_by_class_name('next-events-bucket') icons = div.find_elements_by_class_name('icon-plus') for i in icons: try: i.click() except: print("Exception") games = div.find_elements_by_class_name('coupon-content') for game in games: try: competitors = game.find_element_by_class_name('competitors') teams = competitors.find_elements_by_class_name('competitor-name') print(teams[0].find_element_by_class_name('name').text + " vs." + teams[1].find_element_by_class_name('name').text) odds = game.find_elements_by_class_name('market-type')[1] prices = odds.find_elements_by_class_name('bet-price') new_data = { 'Home': [teams[0].find_element_by_class_name('name').text], 'Away': [teams[1].find_element_by_class_name('name').text], 'BVD_HomeW': [float(prices[0].text)], 'BVD_AwayW': [float(prices[1].text)], 'BVD_Draw': [float(prices[2].text)] } df = df.append(pd.DataFrame(new_data), ignore_index=True, sort=False) except: print("exception")
def is_not_visible(self, locator, timeout=BASE_TIMEOUT): try: wait = WebDriverWait(self.driver, timeout) wait.until( invisibility_of_element((locator['by'], locator['value']))) return True except TimeoutException: return False
def verify_dropdown_disappears(self, *args): for field_name in args: if field_name == "Forgot your password?": locator = self.FORGOT_YOUR_PASSWORD elif field_name == "Other issues with Sign-In": locator = self.OTHER_ISSUES else: raise Exception("No such field name found in the dropdown") self.driver.wait.until(EC.invisibility_of_element(locator))
def setUp(self): path = r"C:\Users\97252\Desktop\Selenium\chromedriver.exe" self.driver = webdriver.Chrome(path) self.driver.get("https://www.advantageonlineshopping.com/#/") self.lCategory=['speakers','tablets','laptops','mice','headphones'] self.driver.maximize_window() WebDriverWait(self.driver, 10).until(EC.invisibility_of_element((By.CLASS_NAME, "loader"))) self.mpage = MainPage(self.driver) self.categorynum = random.randint(0, 4)
def _wait_for_invisibility(self, elem_css, msg=''): """ 等待指定css元素不可见 Arguments: elem_css {str} -- 可见元素的css表达式 """ m = EC.invisibility_of_element((By.CSS_SELECTOR, elem_css)) self.wait.until(m, message=msg)
def wait_element_invisible(self, *locator): try: self.driver.implicitly_wait(10) WebDriverWait(self.driver, 60).until(ec.presence_of_element_located(*locator)) WebDriverWait(self.driver, 60).until(ec.invisibility_of_element(*locator)) except Exception: print("Element is not visible")
def role_is_exists(self, role): driver = self.app.driver wait = WebDriverWait(driver, 1000) el = wait.until( EC.invisibility_of_element((By.CLASS_NAME, "c1-block-overlay"))) return len( driver.find_elements_by_xpath("//span[contains(text(),'" + role.name + "')]")) > 0
def create_issue(self, project, issue_type, summary, description=None, priority=None, assignee=None): self.common_objects.close_timezone_popup() create_button = self.wait.until( expected_conditions.element_to_be_clickable(self.CREATE_BUTTON)) create_button.click() self.wait.until( expected_conditions.presence_of_element_located( self.CREATE_DIALOG)) project_field = self.wait.until( expected_conditions.element_to_be_clickable(self.PROJECT_FIELD)) project_field.clear() project_field.send_keys(project) project_field.send_keys(Keys.RETURN) self.common_objects.wait_until_busy_spinner_hidden() issue_type_field = self.wait.until( expected_conditions.element_to_be_clickable(self.ISSUE_TYPE_FIELD)) issue_type_field.clear() issue_type_field.send_keys(issue_type) issue_type_field.send_keys(Keys.RETURN) self.common_objects.wait_until_busy_spinner_hidden() summary_field = self.wait.until( expected_conditions.element_to_be_clickable(self.SUMMARY_FIELD)) summary_field.clear() summary_field.send_keys(summary) submit_issue_button = self.wait.until( expected_conditions.element_to_be_clickable( self.SUBMIT_ISSUE_BUTTON)) submit_issue_button.click() self.wait.until_not( expected_conditions.invisibility_of_element(self.CREATE_DIALOG)) try: popup_container = self.wait.until( expected_conditions.visibility_of_element_located( self.SUCCESS_POPUP_CONTAINER)) except TimeoutException: print("Failed to post issue") error = self.wait.until( expected_conditions.presence_of_element_located( (By.CSS_SELECTOR, "#create-issue-dialog div.error"))) self.return_result["error_in_field"] = error.get_attribute( "data-field") self.return_result["error_message"] = error.text self.return_result["success"] = False return self.return_result #popup_container = self.driver.find_element(self.POPUP_CONTAINER) issue_key = popup_container.find_element( By.CLASS_NAME, "issue-created-key").get_attribute("data-issue-key") #self.wait.until(expected_conditions.invisibility_of_element(self.POPUP_CONTAINER)) #doesn't work in circle ci container self.return_result["success"] = True self.return_result["issue_key"] = issue_key return self.return_result
def _debug_function(self): self.page.driver.find_element_by_link_text("Object").click() ActionChains(self.page.driver).move_to_element( self.page.driver.find_element_by_link_text("Debugging")).perform() self.page.driver.find_element_by_link_text("Debug").click() # We need to check if debugger plugin is installed or not try: wait = WebDriverWait(self.page.driver, 2) is_error = wait.until( EC.presence_of_element_located( (By.XPATH, "//div[contains(@class,'MuiDialogTitle-root')]" "//div[text()='Debugger Error']"))) except TimeoutException: is_error = None # If debugger plugin is not found if is_error and is_error.text == "Debugger Error": click = True while click: try: self.page.click_modal('OK', True) wait.until( EC.invisibility_of_element( (By.XPATH, "//div[@class ='MuiDialogTitle-root']" "//div[text()='Debugger Error']"))) click = False except TimeoutException: pass self.skipTest( "Please make sure that debugger plugin is properly configured") else: self.page.driver.switch_to.frame( self.page.driver.find_element_by_tag_name('iframe')) wait.until( EC.presence_of_element_located( (By.XPATH, "//span[contains(.,'Hello, pgAdmin4')]"))) self.page.click_element( self.page.driver.find_elements_by_xpath("//button")[2]) wait.until( EC.presence_of_element_located( (By.XPATH, "//td[contains(@class,'test_function') and " "contains(.,'Hello, pgAdmin4')]"))) # Only this tab is vulnerable rest are BackGrid & Code Mirror # control which are already tested in Query tool test case self.page.click_tab("Messages") source_code = self.page.find_by_xpath( "//*[@id='messages']").get_attribute('innerHTML') self._check_escaped_characters( source_code, 'NOTICE: <img src="x" onerror="console.log(1)">', 'Debugger') self._close_debugger()
def login(self, headless=True, wait_time=15, proxy=None): """ Logs user in with the provided credentials User session is stored in the 'cred_root' folder and reused so there is no need to login every time. Pinterest sessions lasts for about 15 days Ideally you need to call this method 3-4 times a month at most. :return python dict object describing the pinterest response """ chrome_options = Options() if headless: chrome_options.add_argument("--headless") if proxy is not None: http_proxy = Proxy() http_proxy.proxy_type = ProxyType.MANUAL http_proxy.http_proxy = proxy http_proxy.socks_proxy = proxy http_proxy.ssl_proxy = proxy http_proxy.add_to_capabilities(chrome_options) chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome('chromedriver', chrome_options=chrome_options) driver.get("https://pinterest.com/login") try: WebDriverWait(driver, wait_time).until( EC.element_to_be_clickable((By.ID, 'email'))) driver.find_element_by_id("email").send_keys(self.email) driver.find_element_by_id("password").send_keys(self.password) logins = driver.find_elements_by_xpath( "//*[contains(text(), 'Log in')]") for login in logins: login.click() WebDriverWait(driver, wait_time).until( EC.invisibility_of_element((By.ID, 'email'))) cookies = driver.get_cookies() self.http.cookies.clear() for cookie in cookies: self.http.cookies.set(cookie['name'], cookie['value']) self.registry.update_all(self.http.cookies.get_dict()) except Exception as e: print("Failed to login", e) driver.close()
def wait_until_element_invisible(self, hook_value, locate_by=False, hook_token=False): ''' Wait for an element to become invisible. hook_value = the value of the hook it self like an xpath or the actual ID of an element. locate_by = the type of hook it is, this will be an XPath or an ID. Please use/import the class "LocateBy" located in the driver_interface as it contains the correct list of locate_by possibilities. ''' locate_by, hook_value = self._check_locate_by(hook_value, locate_by, hook_token) self.wait.until(EC.invisibility_of_element((locate_by, hook_value))) time.sleep(0.5) # Selenium does not play well with SPA's, sometimes executes too fast and interferes with UI component rendering.
def close_gdpr_banner(self): """Dismiss GDPR banner if present.""" self.wait_until(page_loaded_condition) try: banner = self.driver.find_element_by_id('gdpr_notice') except NoSuchElementException: return logger.debug("Clicking GDPR banner 'I Agree' button") banner.find_element_by_id('gdpr_closebutton').click() self.wait_until(EC.invisibility_of_element(banner))
def wait_for_elem(xpath=None, elem=None, is_list=False): if is_list: WebDriverWait(driver, wait_time).until( ec.visibility_of_all_elements_located((By.XPATH, xpath))) elif elem is not None: WebDriverWait(driver, wait_time).until(ec.invisibility_of_element(elem)) elif xpath is not None: WebDriverWait(driver, wait_time).until( ec.visibility_of_element_located((By.XPATH, xpath)))
def click_on_sign_in(context): login_page = Singleton.getInstance(context,LoginPage) sign_in_button = context.browser.find_element(By.CSS_SELECTOR, login_page.locators['sign_in_button']) sign_in_button.click() time.sleep(2) # For captcha you will need to enter the information manually. if ("Insira os caracteres que está vendo" in context.browser.page_source): fill_in_the_field_password(context, context.credential) WebDriverWait(context.browser, 100).until(EC.invisibility_of_element((By.CSS_SELECTOR, '#auth-captcha-image'))) # Script to automate first login verification. text= "Verificação necessária" if (text in context.browser.page_source): click_on_continue(context) verification_number = run_gmail(context) WebDriverWait(context.browser, 100).until(EC.invisibility_of_element((By.CSS_SELECTOR, '#auth-captcha-image'))) context.browser.find_element(By.CSS_SELECTOR, "[name='code']").send_keys(verification_number) context.browser.find_element(By.CSS_SELECTOR, "#a-autoid-0").click() time.sleep(5)
def searchAndSelectDropdown(self, by, field, dropdownClass, *searchStrings): WebDriverWait(self.driver, self.delay).until(EC.invisibility_of_element((By.CLASS_NAME, "spinner-wrapper"))) mainElement = WebDriverWait(self.driver, self.delay).until(EC.presence_of_element_located((by, field))) mainElement.find_element_by_class_name("form-control.text-input.text-input-transparent.ng-untouched.ng-pristine.ng-valid").click() for searchString in searchStrings: for el in mainElement.find_elements_by_class_name(dropdownClass): if searchString == el.text: el.click() break
def set_priority(self, priority: str): WebDriverWait(self.driver, timeout=5, poll_frequency=1, ignored_exceptions=[NoSuchElementException]) \ .until(EC.invisibility_of_element(self.LOADING_INDICATOR)) self.driver.find_element(*self.PRIORITY_VALUE).click() self.driver.find_element(*self.PRIORITY_INPUT).send_keys(priority + "\n") self.driver.find_element(*self.PRIORITY_VALUE).find_element( *self.SUBMIT_BUTTON).click() WebDriverWait(self.driver, timeout=5, poll_frequency=1) \ .until(EC.text_to_be_present_in_element(self.PRIORITY_VALUE, priority))
def acceptDataUsage(self): WebDriverWaitContainer(self.container).wait.until( ec.frame_to_be_available_and_switch_to_it( GoogleHomeLocators.DATA_USAGE_DIALOG)) self.container.instance.find_element( *GoogleHomeLocators.ACCEPT_DATA_USAGE).click() WebDriverWaitContainer(self.container).wait.until( ec.invisibility_of_element(GoogleHomeLocators.DATA_USAGE_DIALOG)) self.container.instance.switch_to.default_content()
def stop_till_spinner_is_invisible(driver): WebDriverWait(driver, 100, poll_frequency=3, ignored_exceptions=[ ElementClickInterceptedException, ElementNotInteractableException ]).until( EC.invisibility_of_element( (By.XPATH, "//div[@class='vld-background']")))
def _wait_until_iframe_disappears(self, driver: selenium.webdriver.Chrome): try: iframe = WebDriverWait(driver, 10).until( EC.invisibility_of_element(( By.CSS_SELECTOR, "iframe[src^='https://www.google.com/recaptcha/api2/anchor?']" ))) return iframe except NoSuchElementException: print("Element not found")
def cerrar_modal(driver): time.sleep(1) close_modal = driver.find_elements_by_xpath(CLOSE_MODAL)[0] driver.execute_script("arguments[0].click();", close_modal) try: WebDriverWait(driver, 5).until( EC.invisibility_of_element((By.XPATH, CLOSE_MODAL))) except TimeoutError as timeout: print('Tiempo excedido en cerrar_modal') print(timeout)
def close_share_dialog(self): try: dialog = self.get_share_dialog() close_button = dialog.find_element_by_css_selector( 'svg.Dialog_close__wPN0y') close_button.click() self.wait.until(EC.invisibility_of_element( self.get_share_dialog())) except NoSuchElementException: pass
def deleting_entry(self): try: del_btn = self.wait.until( EC.element_to_be_clickable((By.XPATH, delete_btn))).click() self.wait.untill( EC.invisibility_of_element((By.CLASS_NAME, pop_up))) return True except: MyLibrary.save_screenshot_picture(self.driver, 'delete_entry') raise
def update_member(self, **kwargs): self.click_by_js(By.CSS_SELECTOR, ".js_edit") element = self.driver.find_element(By.NAME, "username") element.clear() element.send_keys("upname") self.click_by_js(By.CSS_SELECTOR, ".js_save") # todo:添加隐式等待,保存成功消失 WebDriverWait(self.driver, 2).until( expected_conditions.invisibility_of_element( (By.CSS_SELECTOR, ".js_tips")))
def main(): # constants wait = 15 # seconds driver_path = "/usr/bin/geckodriver" tplc_default_ip = "192.168.0.93" progress_wait = 10 # seconds # start webdriver print("Starting webdriver with executable:", driver_path) options = Options() options.headless = True driver = webdriver.Firefox(executable_path=driver_path, options=options) driver.set_window_size(1000, 1000) # smaller can hide login button # get TPLC page tplc_ip = sys.argv[1] if len(sys.argv) >= 2 else tplc_default_ip print("Getting login page using IP:", tplc_ip) driver.get(f"http://{tplc_ip}/") # login print("Writing password") try: driver.find_element_by_id("pcPassword").send_keys("admin") except NoSuchElementException: print( "Could not find pcPassword element, this is generally because another browser is logged in" ) exit() button_login = WebDriverWait(driver, wait).until( EC.element_to_be_clickable((By.ID, "loginBtn"))) button_login.click() print("Clicked log in") # reboot WebDriverWait(driver, wait).until( EC.invisibility_of_element((By.CLASS_NAME, "loading-container-inner"))) print("Main page loaded, clicking reboot") button_reboot = WebDriverWait(driver, wait).until( EC.element_to_be_clickable((By.ID, "top-control-reboot"))) button_reboot.click() print("Clicked reboot, clicking yes") button_ok = WebDriverWait(driver, wait).until( EC.element_to_be_clickable((By.CLASS_NAME, "btn-msg-ok"))) button_ok.click() print("Reboot started") # print progress from popup print(f"Waiting {progress_wait} seconds") time.sleep(progress_wait) print("Progress:", driver.find_element_by_class_name("progressbar-percentage").text) # reboot in progress, exit print("Quitting") driver.quit()
def WaitForInVisible(self, timeoutInSeconds=30): """Wait for the specified element to be visible on the screen. """ self._searchElement() wait = WebDriverWait(self._webdriver, timeoutInSeconds) try: wait.until(ec.invisibility_of_element(self._currentElement)) except: self.testCache.logger_service.logger.exception( "ActionFailure-WaitForInVisible:")
def thereIsNotification(self): element_present = EC.presence_of_element_located( (By.CLASS_NAME, 'uk-notification-message')) WebDriverWait(self.driver, 1).until(element_present) self.driver.execute_script( 'document.getElementsByClassName("uk-close")[0].click()') element_invisible = EC.invisibility_of_element( (By.CLASS_NAME, 'uk-notification-message')) WebDriverWait(self.driver, 2).until(element_invisible)
def test_touchAction(self): """ 打开firefox 打开百度网页 搜索框输入‘selenium测试’ 通过touchAction点击搜索框 滑动到底部,点击下一页 关闭firefox :return: """ self.driver.get("http://www.baidu.com") expected_conditions.invisibility_of_element(self.driver.find_element(By.ID,'kw')) el = self.driver.find_element(By.ID,'kw') expected_conditions.invisibility_of_element(self.driver.find_element(By.ID,'su')) el_search = self.driver.find_element(By.ID,'su') el.send_keys('selenium测试') action = TouchActions(self.driver) action.tap(el_search) action.perform() action.scroll_from_element(el,0,10000).perform()
def login(self): self.driver.get('{}/accounts/login/'.format(self.base_url)) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) log_in_button = self.driver.find_element_by_xpath( "//div[contains(text(), 'Log In')]") ActionChains( self.driver).move_to_element(log_in_button).click().perform() self.wait.until( ec.invisibility_of_element( (By.XPATH, '//*[contains(text(), "Sign up")]')))