def testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFrameIndex(driver, pages): pages.load("frame_switching_tests/deletingFrame.html") iframe = 0 WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe)) # we should be in the frame now killIframe = driver.find_element(By.ID, "killIframe") killIframe.click() driver.switch_to.default_content() addIFrame = driver.find_element(By.ID, "addBackFrame") addIFrame.click() WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe)) WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "success")))
def _ensure_rte_iframe_ready_and_switch_to_it(self): wait.WebDriverWait(self._tester.driver, 15).until( ec.frame_to_be_available_and_switch_to_it('modal-editor-iframe')) # Ensure inputEx has initialized too wait.WebDriverWait(self._tester.driver, 15).until( ec.element_to_be_clickable( (by.By.PARTIAL_LINK_TEXT, 'Close')))
def testExpectedConditionFrameToBeAvailableAndSwitchToItByLocator(self, driver, pages): pages.load("blank.html") with pytest.raises(TimeoutException): WebDriverWait(driver, 1).until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'myFrame'))) driver.execute_script("setTimeout(function(){var f = document.createElement('iframe'); f.id='myFrame'; f.src = '" + pages.url('iframeWithAlert.html') + "'; document.body.appendChild(f)}, 200)") WebDriverWait(driver, 1).until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'myFrame'))) assert 'click me' == driver.find_element_by_id('alertInFrame').text
def select_noble_metal(self): self.driver.switch_to_default_content() WebDriverWait(self.driver, 20).until( EC.presence_of_element_located( (By.ID, "quanbu"))) quanbu_element = self.driver.find_element_by_id("quanbu") quanbu_element.click() #quanbu_element.click() #script = 'perbankAtomLocationTW' + \ # '("PBL200204","",dse_sessionId)' #self.driver.execute_script(script) self.switch_to_content_frame() self.logger.debug("before find noble metal link") noble_metal_xpath = "html/body/div/div/div[6]" + \ "/div/div/div/ul/li[1]/a" WebDriverWait(self.driver, 20).until( EC.presence_of_element_located( (By.XPATH, noble_metal_xpath))) self.logger.debug("after find noble metal link") self.logger.debug("before script") script = 'AtomSerivceSubmit("PBL201311","","","")' self.driver.execute_script(script) self.logger.debug("after script") counter = 0 while counter < 3: found_exception = False try: self.switch_to_content_frame() WebDriverWait(self.driver, 10).until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, "_market"))) WebDriverWait(self.driver, 10).until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, "_left"))) except StaleElementReferenceException as stale_exception: error_msg = "select noble metal: StaleException {0}" error_msg = error_msg.format(stale_exception) self.logger.error(error_msg) print(error_msg) found_exception = True if not found_exception: break time.sleep(10) counter = counter + 1 if counter == 3: raise StaleElementReferenceException( "select noble metal: tried 3 times") return
def testExpectedConditionFrameToBeAvailableAndSwitchToItByLocator(self, driver, pages): if driver.capabilities['browserName'] == 'firefox' and driver.w3c: pytest.xfail("Marionette issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1297551") pages.load("blank.html") with pytest.raises(TimeoutException): WebDriverWait(driver, 1).until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'myFrame'))) driver.execute_script("setTimeout(function(){var f = document.createElement('iframe'); f.id='myFrame'; f.src = '" + pages.url('iframeWithAlert.html') + "'; document.body.appendChild(f)}, 200)") WebDriverWait(driver, 1).until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'myFrame'))) assert 'click me' == driver.find_element_by_id('alertInFrame').text
def testExpectedConditionFrameToBeAvailableAndSwitchToItByLocator(self): self._loadPage("blank") try: WebDriverWait(self.driver, 1).until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'myFrame'))) self.fail("Expected TimeoutException to have been thrown") except TimeoutException as e: pass self.driver.execute_script("setTimeout(function(){var f = document.createElement('iframe'); f.id='myFrame'; f.src = '"+self._pageURL('iframeWithAlert')+"'; document.body.appendChild(f)}, 200)") WebDriverWait(self.driver, 1).until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'myFrame'))) self.assertEqual('click me', self.driver.find_element_by_id('alertInFrame').text)
def switch_to_content_frame(self): self.driver.switch_to_default_content() per_bank_content_frame = WebDriverWait(self.driver, 10).until( EC.frame_to_be_available_and_switch_to_it( (By.ID, "perbank-content-frame"))) #content_frame = self.driver.find_element_by_id("content-frame") content_frame = WebDriverWait(self.driver, 10).until( EC.frame_to_be_available_and_switch_to_it( (By.ID, "content-frame"))) self.logger.debug("switched to content_frame") return
def _switch_to_content_from_popup(self): """Switch back to mainframe after ending popup After popup is closed, must switch back to mainframe and content frame """ print "Switching to main frame" element = WebDriverWait(self.driver, 20).until( EC.frame_to_be_available_and_switch_to_it( (By.ID, "mainFrame") ) ) element = WebDriverWait(self.driver, 20).until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, self.contentFrameName) ) )
def testExpectedConditionFrameToBeAvailableAndSwitchTo(self): self._loadPage("blank") try: WebDriverWait(self.driver, 1).until(EC.frame_to_be_available_and_switch_to_it('myFrame')) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass
def wait_for_correct_document(_): current_url = self.current_url # cache to avoid extra wire calls # if frame switches are failing, uncomment the following line to # help debug: #print "self.current_url = ", current_url if current_url != expected_url: # getting here may have been caused by the previous wait having # been called too soon before the server switched to the right # document. Do it again, just in case. # # if, on the other hand, the cause was that the previous wait # was called an appropriate time, this shouldn't hurt us. # # (one or might FirefoxDriver change might make this # unnecessary. yuck. ideally, Marionette won't have this # problem, and when we switch to it, we'll be able to ditch # this nested wait. we'll see). wait2 = WebDriverWait(self, DEFAULT_WAIT_TIMEOUT) wait2.until(EC.frame_to_be_available_and_switch_to_it(locator)) return False return True
def are_request_queue_values_displayed(self, request_queue_name, processing=0, waiting=0, holding=0): """ Are request queue values displayed in the list with corrected values for processing, waiting, holding :param request_queue_name: Request queue name to verify in the 'Request Queue' list in Preview Generation. :param processing: Process value. :param waiting: Wait value. :param holding: Hold value. :return: True if displayed, otherwise False. """ selected_item = (By.XPATH, "//td[text()='" + request_queue_name + "']") processing_cell = (By.ID, "rve_proc" + request_queue[request_queue_name] + "") waiting_cell = (By.ID, "rve_wait" + request_queue[request_queue_name] + "") holding_cell = (By.ID, "rve_hold" + request_queue[request_queue_name] + "") parent_page = self._driver.current_window_handle try: self._wait.until(ec.frame_to_be_available_and_switch_to_it(self._frame_id)) self._wait.until(lambda s: s.find_element(*selected_item).is_displayed()) actual_processing = self._driver.find_element(*processing_cell).text actual_waiting = self._driver.find_element(*waiting_cell).text actual_holding = self._driver.find_element(*holding_cell).text if actual_processing == processing and actual_waiting == waiting and actual_holding == holding: are_displayed = True else: are_displayed = False finally: self._driver.switch_to_window(parent_page) return are_displayed
def scrape(self): # Load user page user = self.q.pop(0) print 'Scraping user: '******'http://play.spotify.com/user/' + user) WebDriverWait(self.driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[contains(@id, 'user')]"))) # Scrape user name print 'Scraping user name ...' WebDriverWait(self.driver, 20).until(lambda x: self.driver.find_element_by_xpath("//h1[@class='h-title']").text) name = self.driver.find_element_by_xpath("//h1[@class='h-title']").text print name # Scrape recently played artists artists = self.gather('recently-played-artists') for artist in artists: self.store('recent_artists', ['id', 'user'], [artist, user]) # Scrape public playlists playlists = self.gather('public-playlists') for playlist in playlists: self.store('playlists', ['id', 'user'], [playlist, user]) # Scrape following following = self.gather('following') for follow in following: self.store('follows', ['outgoing', 'incoming'], [user, follow]) self.q.append(follow) # Scrape followers followers = self.gather('followers') for follower in followers: self.store('follows', ['outgoing', 'incoming'], [follower, user]) self.q.append(follower)
def testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFrameIndex(self): self.driver.get(self.webserver.where_is("frame_switching_tests/deletingFrame.html")) iframe = 0 WebDriverWait(self.driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe)) # we should be in the frame now killIframe = self.driver.find_element(By.ID, "killIframe") killIframe.click() self.driver.switch_to.default_content() addIFrame = self.driver.find_element(By.ID, "addBackFrame") addIFrame.click() WebDriverWait(self.driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe)) try: WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.ID, "success"))) except WebDriverException: self.fail("Could not find element after switching frame")
def is_frame_available(locator, timeOut=0): ''' Checking whether the given frame is available to switch to.\n If the frame is available it switches the given driver to the specified frame ''' try: _wait(timeOut).until(EC.frame_to_be_available_and_switch_to_it(Element(locator)._get())) except WebDriverException: return False return True
def _Apply(self, driver, test): if self._element_selector is None: driver.switch_to_default_content() else: wt = WebDriverWait(driver, 30) # seconds locator = self._element_selector.tuple() element = wt.until(EC.frame_to_be_available_and_switch_to_it(locator)) return True
def search(self, text): try: element = WebDriverWait(self.driver, 20).until( EC.frame_to_be_available_and_switch_to_it( (By.ID, "mainFrame") ) ) self.driver.find_element_by_id('terms').send_keys(text) searchBtn = self.driver.find_element_by_id("srchButt").click() finally: print 'Done searching for', text
def select_menu_frame(self): self.select_left_frame() element = WebDriverWait(self.driver, 10).until( EC.frame_to_be_available_and_switch_to_it((By.NAME, "menuiframe")) ) # menu_frame = self.driver.find_element_by_name("menuiframe") # self.driver.switch_to.frame(menu_frame) return
def waitForIframe(self, element, timeout=timeout_time): try: #self.assertTrue(self.waitForElementToBePresent(element),"ERROR inside waitForElementToBeClickable(): can't see element "+element) WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located((By.XPATH, element))) WebDriverWait(self.driver, timeout).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, element))) return True except: self.print_exception_info() self.fail("ERROR: Element "+element + " not found or stale in waitForElementToBeClickable()")
def get_print_queue_name(self, row): """ Gets the name of the print queue according its position. """ parent_page = self._driver.current_window_handle try: self._wait.until(ec.frame_to_be_available_and_switch_to_it(self._frame_id)) return self._driver.find_element((By.XPATH, "//tr[" + str(row + 1) + "]/td")).text finally: self._driver.switch_to_window(parent_page)
def click_download_button(self): """ Clicks the Download button. """ parent_page = self._driver.current_window_handle self._driver.find_element(*self._download_button).click() try: self._wait.until(ec.frame_to_be_available_and_switch_to_it(self._progress_frame)) self._wait.until(ec.visibility_of_element_located(self._download_progress_text)) finally: self._driver.switch_to_window(parent_page)
def _ensure_rte_iframe_ready_and_switch_to_it(self): self.wait().until( ec.frame_to_be_available_and_switch_to_it('modal-editor-iframe')) # Ensure inputEx has initialized too close_clickable = ec.element_to_be_clickable( (by.By.PARTIAL_LINK_TEXT, 'Close')) save_clickable = ec.element_to_be_clickable( (by.By.PARTIAL_LINK_TEXT, 'Save')) def both_clickable(driver): return close_clickable(driver) and save_clickable(driver) self.wait().until(both_clickable)
def is_volume_displayed(self, volume_name): """ Returns true if a Volume is displayed. """ parent_page = self._driver.current_window_handle try: self._wait.until(ec.frame_to_be_available_and_switch_to_it(self._frame_id)) volume_value = (By.XPATH, "//th[text()='" + volume_name + "']") return is_element_present(self._driver, *volume_value) finally: self._driver.switch_to_window(parent_page)
def is_pdf_ir_queue_displayed(self, queue_name): """ Returns true if a PDF IR queue is displayed. """ self._wait.until(ec.visibility_of_element_located(self._summary_selected)) parent_page = self._driver.current_window_handle try: self._wait.until(ec.frame_to_be_available_and_switch_to_it(self._frame_id)) queue_value = (By.XPATH, "//td[text()='" + queue_name + "']") return is_element_present(self._driver, *queue_value) finally: self._driver.switch_to_window(parent_page)
def is_hot_folder_displayed(self, server_name): """ Returns true if a Hot Folder is displayed. """ parent_page = self._driver.current_window_handle try: self._wait.until(ec.frame_to_be_available_and_switch_to_it(self._frame_id)) hot_folder_dir = self.get_hot_folder_path(server_name) hot_folder_value = (By.XPATH, "//a[contains(text(),'" + hot_folder_dir + "')]") return is_element_present(self._driver, *hot_folder_value) finally: self._driver.switch_to_window(parent_page)
def delete_print_queue(self, print_queue_name): """ Deletes a print queue. """ if self.is_pdf_ir_queue_displayed(print_queue_name): parent_page = self._driver.current_window_handle self._wait.until(ec.frame_to_be_available_and_switch_to_it(self._frame_id)) self.click_delete_icon(print_queue_name) self.click_delete_button() self._driver.switch_to_window(parent_page) else: print "The " + print_queue_name + " is not present."
def select_left_frame(self): # wait the main frame is ready self.driver.switch_to.default_content() element = WebDriverWait(self.driver, 10).until( EC.frame_to_be_available_and_switch_to_it((By.NAME, "leftFrame")) ) # switch to left frame self.driver.switch_to.default_content() left_frame = self.driver.find_element_by_name("leftFrame") self.driver.switch_to.frame(left_frame) return
def _switch_to_nav_frame(self): """Switch to nav frame where download doc link is placed Attempt to find the nav frame and switch for 20 seconds. If found before 20 seconds, fra,e will switch context to nav frame. """ self.navFrameName = self.contentFrameName.replace("Content", "Nav") self.driver.switch_to.parent_frame() print 'Switching to nav frame', self.navFrameName element = WebDriverWait(self.driver, 20).until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, self.navFrameName) ) )
def _switch_to_results_frame(self): """Switch to results frame where search results are held Attempt to find the results frame and switch for 20 seconds. If found before 20 seconds, fra,e will switch context to results frame. """ contentFrame = self.driver.find_element_by_css_selector("frame[title='Results Content Frame']") self.contentFrameName = contentFrame.get_attribute('name') print 'Switching to content frame', self.contentFrameName element = WebDriverWait(self.driver, 20).until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, self.contentFrameName) ) )
def SwitchFrame(self, frame, tagname=None): """Switch to a different frame in web page. Args: frame: string, frame to switch to. tagname: string, name of iframe tag. Returns: boolean: True = frame switched, False = frame not switched. """ try: if tagname: self.GetWait().until(EC.frame_to_be_available_and_switch_to_it( self.driver.find_element_by_tag_name(tagname))) else: self.GetWait().until(EC.frame_to_be_available_and_switch_to_it(frame)) except TimeoutException: self.logger.error('Timed out finding frame: %s', frame) return False except NoSuchFrameException: self.logger.warning('Frame named %s not found.', frame) return False return True
def switchToFrame(self, locator, expected_url, timeout=DEFAULT_WAIT_TIMEOUT * 2): """ Wait for a frame to become available, then switch to it. Args: - locator: Frame locator string - expected_url: Used to ensure that we've ended up in the new frame. Note that (e.g.) chat window tests will need to append a hash value or something similar to ensure the URL is unique so that switching from one chat window to another does the right thing. Kwargs: - timeout: Operation timeout in seconds Returns: Driver """ wait = WebDriverWait(self, timeout) wait.until(EC.frame_to_be_available_and_switch_to_it(locator)) def wait_for_correct_document(_): current_url = self.current_url # cache to avoid extra wire calls # if frame switches are failing, uncomment the following line to # help debug: #print "self.current_url = ", current_url if current_url != expected_url: # getting here may have been caused by the previous wait having # been called too soon before the server switched to the right # document. Do it again, just in case. # # if, on the other hand, the cause was that the previous wait # was called an appropriate time, this shouldn't hurt us. # # (one or might FirefoxDriver change might make this # unnecessary. yuck. ideally, Marionette won't have this # problem, and when we switch to it, we'll be able to ditch # this nested wait. we'll see). wait2 = WebDriverWait(self, DEFAULT_WAIT_TIMEOUT) wait2.until(EC.frame_to_be_available_and_switch_to_it(locator)) return False return True msg = u"timed out waiting for %s to be %s after %ss seconds" % ( locator, expected_url, timeout) WebDriverWait(self, timeout, poll_frequency=.25).until( wait_for_correct_document, message=msg) return self
def testcyqy_03(self): '''从业主体管理,从业人员管理查询功能''' time.sleep(1) loc2 = ("xpath", "//*[@id = '301e73fd-3b66-4f80-9c30-8ddf8151587d从业人员管理']") dengdai(self.driver, loc2).click() # a = self.driver.find_element_by_xpath("//iframe[starts-with(@src,'../BusinessHandle/ModuleChooicer?fid=')]") # self.driver.switch_to.frame(a) loactor = ("xpath", "//iframe[starts-with(@src,'../BusinessHandle/ModuleChooicer?fid=')]") # 切换iframe WebDriverWait(self.driver, 100).until(EC.frame_to_be_available_and_switch_to_it(loactor)) loc3 = ("xpath", "//*[@id = 'Btn_Seach']") dengdai(self.driver, loc3).click() # 点查询 loactor = ("xpath", "//*[@id='RyglList']/thead/tr/th[5]") element3 = WebDriverWait(self.driver, 100).until(EC.text_to_be_present_in_element(loactor, "职称证书编号")) assert element3
def testcyqy_05(self): '''从业主体管理,企业申请查询功能''' time.sleep(1) loc2 = ("xpath", "//*[@id = '9a19f838-6794-47ba-97c1-b5645e372aea企业申请查询']") dengdai(self.driver, loc2).click() # a = self.driver.find_element_by_xpath("//iframe[starts-with(@src,'../BusinessHandle/ModuleChooicer?fid=')]") # self.driver.switch_to.frame(a) loactor = ("xpath", "//iframe[starts-with(@src,'../BusinessHandle/ModuleChooicer?fid=')]") # 切换iframe WebDriverWait(self.driver, 100).until(EC.frame_to_be_available_and_switch_to_it(loactor)) loc3 = ("xpath", "//*[@id = 'Btn_Seach']") dengdai(self.driver, loc3).click() # 点查询 loactor = ("xpath", "//*[@id='RyglList']/thead/tr/th[5]") element3 = WebDriverWait(self.driver, 100).until(EC.text_to_be_present_in_element(loactor, "网上申请号")) assert element3
def switch_frame_wait(self, locator, timeout=20, poll_frequency=0.5) -> WebElement: # 切换到frame try: wait = WebDriverWait(self.driver, timeout, poll_frequency) element = wait.until( ec.frame_to_be_available_and_switch_to_it(locator)) self.driver.switch_to.default_content() except Exception as e: self.logging.error('frame切换失败{}'.format(e)) raise e return element
def searchweb(self): # the way to locate the button or thing you want on a website in chrome is # by pressing cmd + shift + c and then you can use your mouse to find the # info on the element that you want and you can copy the full xpath. "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "C:/Users/zacka/Desktop/python/networkmonitor/reddit_automations/chromedriver.exe" options = webdriver.ChromeOptions() searchquery = input("Enter the search query please...\n") q = searchquery options.add_argument('--ignore-certificate-errors') options.add_experimental_option("useAutomationExtension", False) options.add_experimental_option("excludeSwitches", ["enable-automation"]) #options.add_argument("--disable-extensions") # optional and off-topic, but it conveniently prevents the popup 'Disable developer mode extensions' # options.add_argument('--incognito') # options.add_argument('--headless') driver = webdriver.Chrome(webdriver1, chrome_options=options) #driver.maximize_window(); action = ActionChains(driver) # doodlechome driver.get('https://www.google.com') WebDriverWait(driver, 10).until( EC.frame_to_be_available_and_switch_to_it( (By.CSS_SELECTOR, "iframe[src^='https://consent.google.com']"))) WebDriverWait(driver, 10).until( EC.element_to_be_clickable( (By.XPATH, "//div[@id='introAgreeButton']"))).click() button = driver.find_element_by_name('q') button.click() button.send_keys(q) button.send_keys(Keys.RETURN) # cuckcuckgo driver = webdriver.Chrome(webdriver1) driver.get('https://www.duckduckgo.com') button = driver.find_element_by_name('q') button.click() button.send_keys(q) button.send_keys(Keys.RETURN) # bingbadabom driver = webdriver.Chrome(webdriver1, chrome_options=options) driver.get('https://www.bing.com') button = driver.find_element_by_name('q') button.click() button.send_keys(q) button.send_keys(Keys.RETURN) input("press ENTER to Exit")
def is_frame_to_be_available_and_switch_to_it(self, locator): ''' 判断frame是否switch进去,能被切入返回ture :param locator:元素 :return:true且switch进去/false ''' try: result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\ (EC.frame_to_be_available_and_switch_to_it(locator)) return result except TimeoutException: return "元素找不到" except NoSuchFrameException: return "元素切不过去"
def into_frame(self, locator): """ 进入frame框架 :param value: frame id 或者 name :return: """ try: WebDriverWait(self.browser, 10).until( EC.frame_to_be_available_and_switch_to_it(locator)) logger.info('进入frame框架成功,定位into_frame的元素为:', locator) except: self.get_shot() logger.error('进入frame框架失败,', locator, '元素无法找到!!!') raise ('进入frame框架失败,', locator, '元素无法找到!!!')
def frame_in(self, frame_name=None, frame_xpath=None, wait_time=40, interval=0.5): if frame_name == None and frame_xpath == None: print("frame_name和frame_xpath,这2个参数不能同时为空,请重新输入") return -1 #可能有错误 elif frame_name != None: WebDriverWait(self.driver, wait_time, interval).until( EC.frame_to_be_available_and_switch_to_it(frame_name)) else: frame = self.driver.find_element_by_xpath(frame_xpath) self.driver.switch_to_frame(frame)
def test_kapx_login_and_logout(self): driver = self.driver # open home page driver.get(self.base_url + "/") # assert for the text "KAPx" in the title self.assertIn("KAPx", driver.title) #except AssertionError as e: self.verificationErrors.append(str(e)) # login by clicking on "Login" button driver.find_element_by_class_name("nav-login").click() # wait for the frame to be available and switch to it wait = WebDriverWait(driver, 5) wait.until( EC.frame_to_be_available_and_switch_to_it( (By.CLASS_NAME, "cboxIframe"))) # wait for presence of text field Username driver.implicitly_wait(1) wait.until(EC.presence_of_element_located((By.NAME, "username"))) # fill up the form on the frame # we can find element by id, xpath, name, link text, class, css etc... login_username = driver.find_element_by_name("username") login_username.clear() login_username.send_keys("TestUserName561") login_password = driver.find_element_by_xpath( "//input[contains(@placeholder, 'Enter your Password')]") login_password.clear() login_password.send_keys("TestPassword1") driver.find_element_by_xpath("//button[contains(.,'Login')]").click() # return to main window driver.switch_to_default_content() # wait for page load and assert for text "Hello TestFirstName" wait.until( EC.text_to_be_present_in_element((By.XPATH, "//p"), "TestFirstName")) self.assertEqual("Hello TestFirstName", driver.find_element_by_xpath("//p").text) #except AssertionError as e: self.verificationErrors.append(str(e)) # logout by clicking on "Logout" button driver.find_element_by_class_name("nav-logout").click() # assert for text "You've signed out successfully" on the main page after logging out wait.until( EC.text_to_be_present_in_element((By.XPATH, "//article/div"), "signed out successfully")) self.assertIn("You've signed out successfully", driver.find_element_by_xpath("//article/div").text)
def testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFrameIndex( self): self.driver.get( self.webserver.where_is( "frame_switching_tests/deletingFrame.html")) iframe = 0 WebDriverWait(self.driver, 3).until( EC.frame_to_be_available_and_switch_to_it(iframe)) # we should be in the frame now killIframe = self.driver.find_element(By.ID, "killIframe") killIframe.click() self.driver.switch_to.default_content() addIFrame = self.driver.find_element(By.ID, "addBackFrame") addIFrame.click() WebDriverWait(self.driver, 3).until( EC.frame_to_be_available_and_switch_to_it(iframe)) try: WebDriverWait(self.driver, 3).until( EC.presence_of_element_located((By.ID, "success"))) except WebDriverException: self.fail("Could not find element after switching frame")
def test_in_treeviewer(self): """ Test a wiki popup within the treeviewer itself, rather than a standalone page. For simplicity, most of the other tests in this file will work on the pages outside of the viewer, but we should at least check one within the viewer """ self.browser.get(base_url + 'life.html/@={0}?pop=ol_{0}#x0,y0,w1'.format(self.humanOTT)) wait = WebDriverWait(self.browser, 10) # 10 seconds should be enough to load and pop up a tab wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, ".popup-container .wiki iframe"))) #this iframe should exist and contain a footer of class "wikipage-source" sleep(2) #not sure what we need this... wait = WebDriverWait(self.browser, 30) wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "footer.wikipage-source"))) self.browser.switch_to.default_content()
def login(self): self.driver.get( "https://golestan.sbu.ac.ir/Forms/AuthenticateUser/main.htm") inLogin = True while (inLogin): try: self.waiter.until( EC.frame_to_be_available_and_switch_to_it( (By.ID, 'Faci1'))) self.waiter.until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, 'Master'))) self.waiter.until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, 'Form_Body'))) self.waiter.until(EC.element_to_be_clickable( (By.ID, 'F80351'))).send_keys(self.username) self.driver.find_element_by_id('F80401').send_keys( self.password + Keys.ENTER) inLogin = False except TimeoutException: inLogin = True return self
def wait_until(bc, locator, type=1): '''bc=driver,类似locator=(By.ID,'kw'),type{1:visible,2:clickable,3:frame switch}''' wait = wwait(bc, 10, 0.2) if type == 1: # 等待页面元素可见,返回该页面元素 return wait.until(EC.visibility_of_element_located(locator)) elif type == 2: # 等待页面元素可点击,返回该元素 return wait.until(EC.element_to_be_clickable(locator)) elif type == 3: # 通过定位frame 切换到这个frame return wait.until(EC.frame_to_be_available_and_switch_to_it(locator)) else: return None
def Sign_In_Notifications(driver): t = open("signin.txt", "r") id_username = t.readline() id_password = t.readline() driver.implicitly_wait(5) username = driver.find_element_by_id("username") username.send_keys(id_username) next_button = driver.find_element_by_id("next_button") next_button.click() time.sleep(1) password = driver.find_element_by_id("password") password.send_keys(id_password) submit_button = driver.find_element_by_css_selector("button[type='submit']") submit_button.click() driver.implicitly_wait(10) time.sleep(3) try: accept = driver.find_element_by_id('onetrust-accept-btn-handler') accept.click() except NoSuchElementException: pass close = driver.find_element_by_class_name("close") close.click() ''' WebDriverWait(driver, 90).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='kampyleInvite']"))) driver.implicitly_wait(90) not_right_now_button = driver.find_element_by_id("kplDeclineButton") not_right_now_button.click() driver.switch_to_default_content() ''' driver.implicitly_wait(3) feedback_button = driver.find_element_by_class_name("opt-feedback-link") feedback_button.click() WebDriverWait(driver, 90).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='kampyleForm32024']"))) driver.implicitly_wait(5) close2 = driver.find_element_by_xpath("//button[@ng-if='isShowFormCloseButton()']") close2.click() driver.switch_to_default_content() return
def input_sms_code(self, code) -> None: logger.info("Вводит смс код") try: self.wait.until( EC.frame_to_be_available_and_switch_to_it( CurrencyLocators.FRAME_CONFIRM ) ) element = self.app.wd.find_element(*CurrencyLocators.SMS_CODE_INPUT) element.send_keys(code) except (NoSuchWindowException, TimeoutException): self.wait.until(EC.element_to_be_clickable(CurrencyLocators.SMS_CODE_INPUT)) element = self.app.wd.find_element(*CurrencyLocators.SMS_CODE_INPUT) element.send_keys(code)
def __write_post(self, my_post): # my_post 는 post 클래스의 인스턴스 입니다. VERY_LONG_TIME = Ampu.VERY_LONG_TIME LONG_TIME = Ampu.LONG_TIME SHORT_TIME = Ampu.SHORT_TIME driver = self.__driver menu_name = my_post.menu_name subject_text = my_post.title images = my_post.image_list # 글작성클릭 try: driver.switch_to.default_content() except selenium_exception.NoSuchFrameException: pass try: post_write_button = WebDriverWait(driver, LONG_TIME).until( EC.element_to_be_clickable((By.CLASS_NAME, 'cafe-write-btn'))) except selenium_exception.TimeoutException: raise LoginFailedError('[e:@Ampu.__write_post] 로그인 요망') post_write_button.click() # 메뉴 선택 driver.switch_to.frame('cafe_main') menu_box = Select(driver.find_element_by_name('menuid')) menu_box.select_by_visible_text(menu_name) # 제목 입력 driver.find_element_by_id('subject').click() driver.find_element_by_id('subject').send_keys(subject_text) # 이미지 업로드 divided_images_list = Ampu.divide_images_list_by_size(images) for divided_images in divided_images_list: multi_file_path = Ampu.make_multi_file_path(divided_images) self.__upload_images(multi_file_path) # 게시글 등록 WebDriverWait(driver, LONG_TIME).until( EC.frame_to_be_available_and_switch_to_it((By.ID, "cafe_main"))) driver.execute_script('oCafeWrite.preCafeWriteContents()') # 게시글 등록이 완료될 때 까지 대기 WebDriverWait(driver, LONG_TIME).until_not( EC.presence_of_element_located((By.ID, 'cafePreviewBtn')))
def _switch_to_results_frame(self): """Switch to results frame where search results are held Attempt to find the results frame and switch for 20 seconds. If found before 20 seconds, fra,e will switch context to results frame. """ contentFrame = self.driver.find_element_by_css_selector( "frame[title='Results Content Frame']") self.contentFrameName = contentFrame.get_attribute('name') print 'Switching to content frame', self.contentFrameName element = WebDriverWait(self.driver, 20).until( EC.frame_to_be_available_and_switch_to_it( (By.NAME, self.contentFrameName)))
def get_cur(self): self.wait.until( EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe"))) lession = self.driver.find_element_by_class_name('clearfix') print('你已选择课程[{}]\n----------------------------------'.format( lession.text.encode("utf-8"))) duration = self.driver.find_element_by_xpath( '/html/body/div/div[2]/div[2]/ul/li[1]/div[2]/p[4]') print(duration.text) url = lession.find_elements_by_tag_name('a')[0].get_attribute( 'href').encode("utf-8") self.driver.get(url) a = self.driver.find_element_by_class_name('articlename') a.click()
def load_ga_js_test_page(self, timeout=12): # TODO update to pbtest.org URL # TODO and remove the HTML pages from eff.org then self.load_url(SurrogatesTest.TEST_URL) wait = WebDriverWait(self.driver, timeout) try: wait.until( EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, 'iframe')) ) return wait.until(EC.text_to_be_present_in_element( (By.CSS_SELECTOR, 'h1'), "It worked!" )) except TimeoutException: return False
def frameToBeAvailableAndSwtichToIt(self, by, locator): ''' 检查frame是否存在,存在就切换到frame中 :param by: :param locator: :return: ''' try: if by.lower() in self.byDic: self.wait.until(EC.frame_to_be_available_and_switch_to_it((self.byDic[by.lower()], locator))) else: raise TypeError('未找到定位方式,请确保定位方式正确') except Exception as e: raise e
def switch_to_iframe(self, loc, loc_msg=""): """ :funcation:html切换到内嵌的iframe中 :param loc: 元素定位表达式 :param loc_msg: 功能页面page的描述 :return: """ try: WebDriverWait(self.driver, 30, 0.5).until( EC.frame_to_be_available_and_switch_to_it(loc)) logger.info(" {} 成功切换到此iframe中".format(loc_msg)) except: logger.exception(" {} 切入alert弹框失败".format(loc_msg)) self.save_web_screenshot(loc_msg)
def send_message(self, message, attach=None): chat_form = self.browser.find_element_by_css_selector( 'form.reply-wrapper div.holder') chat_form.click() uploading_failed = False if attach: file_input = self.browser.find_element_by_css_selector( 'input#attachs') file_input.send_keys(attach) css = 'div.next-upload-list-item:last-child' div = WebDriverWait(self.browser, 15).until( EC.presence_of_element_located((By.CSS_SELECTOR, css))) try: WebDriverWait(self.browser, 150).until( element_has_css_class(div, 'next-upload-list-item-done')) except TimeoutException: print('time out, cancel uploading') div.find_element_by_css_selector('i.next-icon-close').click() uploading_failed = True if uploading_failed: return False # if uploading_failed or attach is None: # doc = pq(message) # doc.find('span.attach').remove() # message = doc.outer_html() WebDriverWait(self.browser, 15).until( EC.frame_to_be_available_and_switch_to_it( (By.CSS_SELECTOR, '#inquiry-content_ifr'))) js = self.reply_js_template.format(message=message) self.browser.execute_script(js) time.sleep(1) body = self.browser.find_element_by_tag_name('body') self.click(body) self.browser.switch_to.default_content() btn_send = self.browser.find_element_by_css_selector( 'form.reply-wrapper button.send') btn_send.click() time.sleep(1) return True
def switch_iframe(self, value): """ web方法,切换iframe :param value: iframe的xpath路径 :return: """ try: self.webdriver_wait.until( EC.frame_to_be_available_and_switch_to_it((By.ID, value))) except Exception as e: with allure.step('未发现元素截图'): allure.attach(self.webdriver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG) assert False, "Not Found The iframe " + value
def _switch_to_main_frame(self, faci_id): """ Golestan uses frames. To access main body of page, we need to switch between its frames This function switches driver to main frame of page (the contents) :param faci_id: Golestan frames has a Faci_id which is the id of that frame. According to our usage, we need to navigate to different Faci_ids. """ WebDriverWait(self.driver, 50) \ .until(ec.frame_to_be_available_and_switch_to_it((By.XPATH, f"""//*[@id="Faci{faci_id}"]"""))) frame = self.driver.find_element_by_xpath( '/html/frameset/frameset/frame[2]') self.driver.switch_to.frame(frame) frame = self.driver.find_element_by_xpath('/html/frameset/frame[3]') self.driver.switch_to.frame(frame)
def load_ga_js_test_page(self): # TODO update to pbtest.org URL # TODO and remove the HTML pages from eff.org then self.load_url( "https://www.eff.org/files/pbtest/ga_js_surrogate_test.html") wait = WebDriverWait(self.driver, WAIT_TIMEOUT) wait.until( EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, 'iframe'))) try: return wait.until( EC.text_to_be_present_in_element((By.CSS_SELECTOR, 'h1'), "It worked!")) except TimeoutException: return False
def frame_by_element(self, element: Element, timeout: int = 0): """ Switch the driver's context to the given frame element. Args: element (Element): The frame element to switch to timeout: The number of seconds to wait for the frame to be switched to. Examples: iframe = py.get('iframe') py.switch_to.frame_by_element(iframe) """ self._py.log.info('[STEP] py.switch_to.frame_by_element() - Switch to frame using an Element.') self._py.wait(timeout).until(ec.frame_to_be_available_and_switch_to_it(element.locator)) return self._py
def frame(self, name_or_id: str, timeout: int = 0): """ Switch the driver's context to the new frame given the name or id of the element. Args: name_or_id: The frame's `id` or `name` attribute value timeout: The number of seconds to wait for the frame to be switched to. Examples: # Switch to an iframe py.switch_to.frame('main-frame') """ self._py.log.info(f'[STEP] py.switch_to.frame() - Switch to frame using name or id: ``{name_or_id}``') self._py.wait(timeout).until(ec.frame_to_be_available_and_switch_to_it(name_or_id)) return self._py
def setUp(self): chrome_options = Options() # chrome_options.add_argument("--headless") driver_location = os.path.abspath("C:\\bin\\chromedriver.exe") self.driver = webdriver.Chrome(options=chrome_options, executable_path=driver_location) app_url = 'https://mingle-ci01-portal.mingle.awsdev.infor.com' tenant_id = 'CI_TST' idm_logical_id = 'lid://infor.daf.daf' self.driver.get( "{}/{}?favoriteContext=$screenId=daf_search&LogicalId={}".format( app_url, tenant_id, idm_logical_id)) login_button = self.driver.find_element_by_link_text( "Cloud Identities") login_button.click() username_field = self.driver.find_element_by_id("username") password_field = self.driver.find_element_by_id("password") submit_button = self.driver.find_element_by_link_text("Sign On") username_field.send_keys("") password_field.send_keys("") submit_button.click() # wait for app switcher WebDriverWait(self.driver, 10).until( expected_conditions.visibility_of_element_located( (By.ID, "mhdrAppBtn"))) # wait for first frame # WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located((By.TAG_NAME, "iframe"))) # find client top frame WebDriverWait(self.driver, 10).until( expected_conditions.frame_to_be_available_and_switch_to_it( (By.XPATH, "//iframe[contains(@name, \"daf_\")]"))) WebDriverWait(self.driver, 20).until( expected_conditions.frame_to_be_available_and_switch_to_it( (By.ID, "clientFrame")))
def get_availability(data, driver): """ Returns apartment availability information """ url = data['url'] content = [] log.info(f'Processing {url}') driver.get(url) delay = 60 # seconds try: WebDriverWait(driver, delay).until( EC.frame_to_be_available_and_switch_to_it('rp-leasing-widget')) WebDriverWait(driver, delay).until(EC.presence_of_element_located( (By.XPATH, "//button[contains(@class, 'primary')][contains(text(), 'Start')]"))) except TimeoutException: log.info(f'Page did not load: {url}') return content try: driver.find_element_by_xpath( "//button[contains(@class, 'primary')][contains(text(), 'Start')]").click() WebDriverWait(driver, delay).until( EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'floorplan-tile')]/div/span[contains(@class, 'name')]"))) # Print plan prices names = [n.text for n in driver.find_elements_by_xpath( "//div[contains(@class, 'floorplan-tile')]/div/span[contains(@class, 'name')]")] specs = [n.text for n in driver.find_elements_by_xpath( "//div[contains(@class, 'floorplan-tile')]/div/span[contains(@class, 'specs')]")] prices = [n.text for n in driver.find_elements_by_xpath( "//div[contains(@class, 'floorplan-tile')]/div/span[contains(@class, 'range')]")] availability = [n.text for n in driver.find_elements_by_xpath( "//div[contains(@class, 'floorplan-tile')]/div[@class='tile-buttons']/button")] except Exception: log.exception(f'Unable to parse {url}') return content for i in range(len(names)): match = re.match( r'\((\d+)\).*', availability[i]) if len(availability) > i else None units = int(match.groups()[0]) if match else '0' match = re.match( r'(\$\d*)( \- \$\d*\*)*', prices[i].split(' - ')[0].replace(',', '').replace('From ', '')) if len(prices) > i else None min_price = match.groups()[0] if match else '$0' content.append((names[i], specs[i], min_price, str(units))) return {'meta': data, 'data': content}
def _write_to_text_area(webdriver, element, input_text, interaction): # Rich Text Editor if "richeditor-cover" in element.get_attribute("class"): attribute_id = element.get_attribute("id") iframe_xpath = f"//div[textarea[@id='{attribute_id}']]//iframe" _wait_until( webdriver, EC.frame_to_be_available_and_switch_to_it( (By.XPATH, iframe_xpath)), interaction) # Send keys seems flaky when using Rich Text Editor (tinymce). Make the "input_text" small. webdriver.find_element_by_id("tinymce").send_keys(input_text) webdriver.switch_to.parent_frame() # Plain text else: element.send_keys(input_text)
def switch2board(self): # 找到留言板按钮 WebDriverWait(self.__driver, 10).until( EC.presence_of_element_located( (By.XPATH, '//a[@title="留言板"]'))).click() # 黄钻过期提醒 # WebDriverWait(self.__driver, 10).until( # EC.presence_of_element_located((By.ID, "dialog_button_1")) # ).click() # 确保留言板所在的frame已经加载完并切换 WebDriverWait(self.__driver, 10).until( EC.frame_to_be_available_and_switch_to_it( (By.XPATH, '//iframe[@id="tgb"]')))