def test_it(self): browser.get(self.login_url) self.assertEqual(browser.title, 'Auth Page') browser.find_element_by_id('openid').submit() login = WebDriverWait(browser, 2).until( EC.presence_of_element_located((By.NAME, 'user_name'))) self.assertEqual(browser.title, 'Sign In') login.send_keys(self.login) passwd = browser.find_element_by_name('password') passwd.send_keys(self.password) passwd.submit() find_alert = EC.alert_is_present() find_continue = EC.presence_of_element_located( (By.ID, 'continue-button')) result = WebDriverWait(browser, 2).until( lambda driver: find_alert(driver) or find_continue(driver)) if isinstance(result, Alert): alert = browser.switch_to_alert() else: result.click() alert = WebDriverWait(browser, 2).until(EC.alert_is_present()) alert.accept() result = WebDriverWait(browser, 2).until( EC.presence_of_element_located((By.ID, 'result'))) self.assertEqual(browser.title, 'Result Page') result = json.loads(result.text) self.assertTrue('profile' in result) self.assertTrue('credentials' in result) profile = result['profile'] self.assertTrue('name' in profile) self.assertTrue('accounts' in profile)
def test_HandleFrame(self): from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException url = "http://127.0.0.1/frameset.html" # 访问自动以测试网页 self.driver.get(url) # 使用索引方式进入指定的frame页面,索引号从0开始。 # 所以想进入中间的frame,需要使用索引号1 # 如果没有使用此行代码,则无法找到页面中左侧frame中的任何页面元素 self.driver.switch_to.frame(0) # 找到左侧frame中的p标签元素 leftFrameText = self.driver.find_element_by_xpath("//p") # 断言左侧frame中的文字是否和“这是左侧 frame 页面上的文字”几个关键字相一致 self.assertAlmostEqual(leftFrameText.text, u"这是左侧 frame 页面上的文字") # 找到左侧frame中的按钮元素,并点击该元素 self.driver.find_element_by_tag_name("input").click() try: # 动态等待alert窗体出现 alertWindow = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) # 打印alert消息 print alertWindow.text alertWindow.accept() except TimeoutException, e: print e
def execute_tasks(browser, tasks): main_window = browser.window_handles for i in range(len(tasks)): id = browser.find_element_by_id(i + 1) ActionChains(browser).double_click(id).perform() WebDriverWait(browser, 10).until( expected_conditions.new_window_is_opened(main_window)) windows = browser.window_handles for w in windows: if w != main_window[0]: browser.switch_to.window(w) filename = os.path.join(os.getcwd(), "files", (tasks[i] + ".xls")) try: browser.find_element_by_id("FILE").send_keys(filename) browser.find_element_by_id("save").click() except Exception as e: print(f"{filename} -- {RED}不成功{END}") print(f"{RED}{e}{END}") else: alert = WebDriverWait(browser, 10).until( expected_conditions.alert_is_present()) alert.accept() print(f"{filename} -- {GREEN}已上传{END}") finally: browser.close() browser.switch_to.window(main_window[0])
def delCourseContents(d): print "Deleting From Course" d.find_element_by_xpath( "//th[text()[contains(.,'/courses')]]/span/a").click() d.find_element_by_partial_link_text("Open").click() WebDriverWait(d, MAX_WAIT).until( EC.presence_of_element_located( (By.ID, "listContainer_selectAll"))).click() d.find_element_by_xpath( "//label[text()[contains(.,'Recycle Bin')]]").click() print "Unselected recycle bin" d.find_element_by_partial_link_text("Delete").click() deleteAlert = WebDriverWait(d, MAX_WAIT).until(EC.alert_is_present()) deleteAlert = tester.driver.switch_to.alert if deleteAlert: deleteAlert.accept() print "Pressed delete, this could take up to 10 minutes" # Super long delay try: WebDriverWait(d, 600).until( EC.presence_of_element_located((By.ID, "badMmsg1"))) error = d.find_element_by_id('badMsg1').text print "Deleting from course: " + error if str(error).contains("Failure deleting content."): d.find_element_by_partial_link_text("Recycle Bin").click() print "Recursing into the recycle bin" delCourseContents(d) except: traceback.print_exc() print "Done deleting from course" return
def test_3_del_definition_group(browser, help): # заходим в главное меню регламенты - группы регаламентов href = '[href="#/definition_groups"]' help.definition(browser, href) # Ищем строку ИЗМЕНЕННАЯ ТЕСТОВАЯ ГРУППА РЕГЛАМЕНТОВ line_definition = browser.find_elements_by_css_selector( '[class="text-pointer"]') deleg_definition = browser.find_element_by_xpath( '//b[text()="ИЗМЕНЕННАЯ ТЕСТОВАЯ ГРУППА РЕГЛАМЕНТОВ"]' ) # ИЗМЕНЕННАЯ ТЕСТОВАЯ ГРУППА РЕГЛАМЕНТОВ"]') deleg_definition.click() i = 0 while line_definition[i] != deleg_definition: i += 1 time.sleep(2) # browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") # удаляем группу регламентов selector = '[class="remove-icon text-black"]' help.f_selectors(browser, selector, i) # подтвердить удаление alert = WDW(browser, 10).until(EC.alert_is_present()) alert.accept() time.sleep(1) # Проверяем отсутствие измененной тестовой группы регламентов xpath = '//*[text() = "ИЗМЕНЕННАЯ ТЕСТОВАЯ ГРУППА РЕГЛАМЕНТОВ"]' assert help.check_no_exists_by_xpath( browser, xpath), "Тестовая группа регламентов не удалена"
def test_alert(self): driver = self.driver # alert = driver.switch_to_alert() alert = WebDriverWait(driver, 5).until(expected_conditions.alert_is_present()) self.assertEqual('', alert.text) alert.accept()
def test_compare_products_removal_alert(self): # get the search textbox search_field = self.driver.find_element_by_name("q") search_field.clear() # enter search keyword and submit search_field.send_keys("dress") search_field.submit() # click the Add to compare link self.driver.find_element_by_link_text("Add to Compare").click() # wait for Clear All link to be visible clear_all_link = WebDriverWait(self.driver, 10) \ .until(expected_conditions.visibility_of_element_located((By.LINK_TEXT, 'Clear All'))) # click on Clear All link, # this will display an alert to the user clear_all_link.click() # wait for the alert to present alert = WebDriverWait(self.driver, 10) \ .until(expected_conditions.alert_is_present()) # get the text from alert alert_text = alert.text # check alert text self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text) # click on Ok button alert.accept()
def delCourseContents(d): print "Deleting From Course" d.find_element_by_xpath("//th[text()[contains(.,'/courses')]]/span/a").click() d.find_element_by_partial_link_text("Open").click() WebDriverWait(d, MAX_WAIT).until(EC.presence_of_element_located((By.ID, "listContainer_selectAll"))).click() d.find_element_by_xpath("//label[text()[contains(.,'Recycle Bin')]]").click() print "Unselected recycle bin" d.find_element_by_partial_link_text("Delete").click() deleteAlert = WebDriverWait(d, MAX_WAIT).until(EC.alert_is_present()) deleteAlert = tester.driver.switch_to.alert if deleteAlert: deleteAlert.accept() print "Pressed delete, this could take up to 10 minutes" # Super long delay try: WebDriverWait(d, 600).until(EC.presence_of_element_located((By.ID, "badMmsg1"))) error = d.find_element_by_id("badMsg1").text print "Deleting from course: " + error if str(error).contains("Failure deleting content."): d.find_element_by_partial_link_text("Recycle Bin").click() print "Recursing into the recycle bin" delCourseContents(d) except: traceback.print_exc() print "Done deleting from course" return
def test_handleFrame(self): url = 'F:\\HTMLTest\\41\\frameset.html' self.driver.get(url) self.driver.switch_to.frame(0) leftFrameText = self.driver.find_element_by_xpath('//p') self.assertAlmostEqual(leftFrameText.text, '这是左侧 frame 页面上的文字') self.driver.find_element_by_tag_name('input').click() try: alertWindow = WebDriverWait(self.driver, 10, 0.2).until(EC.alert_is_present()) print(alertWindow.text) alertWindow.accept() except TimeoutException as e: print(e) self.driver.switch_to.default_content() self.driver.switch_to.frame( self.driver.find_elements_by_tag_name('frame')[1]) assert '这是中间 frame 页面上的文字' in self.driver.page_source self.driver.find_element_by_tag_name('input').send_keys('我在中间 frame') self.driver.switch_to.default_content() self.driver.switch_to.frame( self.driver.find_element_by_id('rightframe')) assert '这是右侧 frame 页面上的文字' in self.driver.page_source self.driver.switch_to.default_content()
def test_case(self): self.driver.switch_to.frame(0) leftframetext = self.driver.find_element_by_xpath("//p") print(leftframetext.text) self.assertEqual(leftframetext.text, u"这是左侧 frame 页面上的文字") self.driver.find_element_by_xpath("/html/body/input").click() try: alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) #获取到弹出框 print(alert.text) alert.accept() #点击弹出框的确定按钮 except TimeoutException as e: print(e) self.driver.switch_to.default_content() #退出当前iframe才能进入到其他的iframe self.driver.switch_to.frame("middleframe") self.assertIn("这是中间frame上的文字", self.driver.page_source, "The result is fail") self.driver.find_element_by_xpath('''//*[@id="text"]''').send_keys( "这是一个输入框") time.sleep(2) self.driver.switch_to.default_content() self.driver.switch_to.frame("rightframe") self.assertIn("这是右间frame上的文字", self.driver.page_source, "the result is fail") print("done")
def get(self): self.driver.get(self.dic_url[self.sid]) if self.sid == 'SWGS': try: self.driver.switch_to_alert() alert = WebDriverWait(self.driver, 1).until(EC.alert_is_present()) alert.accept() except NoAlertPresentException: pass finally: while True: try: WebDriverWait(self.driver, 0).until(EC.element_to_be_clickable((By.ID, 'bodyBlock'))) except: break try: WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.ID, 'mdi01_subWindow0_iframe'))) finally: print('Page is ready!') self.driver.execute_script('''top.document.title = "(FOR AUTO TEST TOOL)"''') # Recorder 선언 self.recorder = Recorder(self.driver) self.recorder.addEventListener()
def maybealert(browser, timeout): ## 等待页面完全载入完成 try: wait_for_page_load(browser) except: pass texts="" #### 获得 driver 属性 drivertypes = drivertype() if drivertypes ==5 or drivertypes ==15 or drivertypes ==25 : # phantomjs , 容器 htmlunitjs , 远程 htmlunitjs. 注意: 其他模式不操作 # 需要在操作前提前注入脚本 acceptbyalert_beforedo_ghostdriver(browser) texts=u"GhostDriver模式,未获取" ### 这里是 Phantomjs 或 Htmlunit 模式判断的返回 return (texts) else: try: alert=WebDriverWait(browser, timeout).until(EC.alert_is_present()) alert.accept() ##进行了选择 texts=alert.text except TimeoutException: pass except NoAlertPresentException: pass finally: return (texts) ## 返回具体信息, 以便一些错误弹出窗体的信息判断 , 必须在 finally 返回, 否则其它异常会抛出
def test_it(self): browser.get(self.login_url) self.assertEqual(browser.title, 'Auth Page') browser.find_element_by_id('openid').submit() login = WebDriverWait(browser, 2).until( EC.presence_of_element_located((By.NAME, 'user_name'))) self.assertEqual(browser.title, 'Sign In') login.send_keys(self.login) passwd = browser.find_element_by_name('password') passwd.send_keys(self.password) passwd.submit() find_alert = EC.alert_is_present() find_continue = EC.presence_of_element_located( (By.ID, 'continue-button')) WebDriverWait(browser, 2).until( lambda driver: find_alert(driver) or find_continue(driver)) continue_btn = browser.find_element_by_id('continue-button') if continue_btn: continue_btn.click() alert = WebDriverWait(browser, 2).until(EC.alert_is_present()) else: alert = browser.switch_to_alert() alert.accept() result = WebDriverWait(browser, 2).until( EC.presence_of_element_located((By.ID, 'result'))) self.assertEqual(browser.title, 'Result Page') result = json.loads(result.text) self.assertTrue('profile' in result) self.assertTrue('credentials' in result) profile = result['profile'] self.assertTrue('name' in profile) self.assertTrue('accounts' in profile)
def test_compare_products_removal_alert(self): # get the search textbox search_field = self.driver.find_element_by_name("q") search_field.clear() # enter search keyword and submit search_field.send_keys("phones") search_field.submit() # click the Add to compare link self.driver.\ find_element_by_link_text("Add to Compare").click() # wait for Clear All link to be visible clear_all_link = WebDriverWait(self.driver, 10)\ .until(expected_conditions.visibility_of_element_located((By.LINK_TEXT, "Clear All"))) # click on Clear All link, # this will display an alert to the user clear_all_link.click() # wait for the alert to present alert = WebDriverWait(self.driver, 10)\ .until(expected_conditions.alert_is_present()) # get the text from alert alert_text = alert.text # check alert text self.assertEqual("Are you sure you would like to remove all products from your comparison?", alert_text) # click on Ok button alert.accept()
def test_HandleFrame(self): from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By import traceback import time url='F:\gitstorehouse\selenium3.0\webdriverAPI接口\测试页面\\frameset.html' self.driver.get(url) #使用索引的方式进入frame time.sleep(5) self.driver.switch_to.frame(0) leftframetext = self.driver.find_element_by_xpath('/html/body/p') self.assertEqual(leftframetext.text,'这是左侧frame 页面的信息') self.driver.find_element(By.XPATH,'/html/body/input').click() try: alertwindow = WebDriverWait(self.driver,10,1).until(EC.alert_is_present()) print(alertwindow.text) alertwindow.accept() except TimeoutException as e: print(traceback(e)) self.driver.switch_to.default_content() #通过页面标签对象定位 self.driver.switch_to.frame(self.driver.find_elements(By.TAG_NAME,'frame')[1]) assert '这是中间frame' in self.driver.page_source self.driver.find_element(By.TAG_NAME,'input').send_keys('中间') #返回最外层 self.driver.switch_to.default_content() # 通过页面标签对象定位 self.driver.switch_to.frame(self.driver.find_element(By.ID,'rightframe')) assert '这是右侧frame页面上的文字' in self.driver.page_source self.driver.switch_to.default_content()
def test_remove_user(self): self.test_login() self.driver.get('http://127.0.0.1:5000/profile') remove_button = self.driver.find_element_by_id('delete_user') remove_button.click() alert = WebDriverWait(self.driver, 10).until(expected_conditions.alert_is_present()) alert.accept()
def interactionWithAlerts(self, accept=True): alert_element = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) alert_text = alert_element.text print(alert_text) if accept is True: alert_element.accept() else: alert_element.dismiss()
def acessarIntegra(self): try: elem = self.driver.find_element_by_link_text( "Acesso íntegra do processo") except Exception as e: return self.driver.get(elem.get_attribute("href")) alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) alert.accept()
def print_secret_code(self): try: alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) alert_text = alert.text secret_code = alert_text.split()[-1] print(secret_code) alert.accept() except NoAlertPresentException: print("No second alert presented")
def get_alert_text(self, opt='accept', timeout=10): a = WebDriverWait(self.driver, timeout).until( expected_conditions.alert_is_present()) t = a.text if opt == 'accept': a.accept() else: pass return t
def solve_quiz_and_get_code(self): try: alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) alert_text = alert.text x = int(alert_text.split()[2]) answer = str(math.log(abs((12 * math.sin(float(x)))))) alert.send_keys(answer) alert.accept() except NoAlertPresentException: print("No first alert presented")
def alert_accept(self): ''' 切换到弹框并确认 :return: ''' try: alert = WebDriverWait(BaseUI.driver, 5, 0.5).until(EC.alert_is_present) alert.accept() except: log_tool.error("切换弹窗失败,当前页面不存在弹窗") raise self.shot("弹框确定操作")
def accept_location_popup(self, secondstowait=DefaultTimeouts.DEFAULT_TIMEOUT): logger.debug("Attempting to accept Location Popup..") try: alert = WebDriverWait(self._driver, secondstowait).until( EC.alert_is_present(), 'Timed out waiting for Location Services ' + 'confirmation popup to appear.') alert.accept() except Exception as e: logger.debug("Failed to accept alert: {}".format(e.message)) raise
def upload_file(self): """Uploading file""" upload_button = self.driver.find_element(*DownloadFileLocators.UPLOAD_BUTTON) upload_button.click() file_input = self.driver.find_elements(*DownloadFileLocators.FILE) if file_input: dirname = os.path.dirname(__file__) filename = os.path.join(dirname, "pylint.png") file_input[0].send_keys(filename) alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) alert.accept() save_button = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located(DownloadFileLocators.SAVE_BUTTON)) save_button.click() assert file_input
def test_clean(browser, help): # заходим в главное меню регламенты - регаламенты href = '[href="#/definitions"]' help.definition(browser, href) # Выбираем строку Регламента для создания делегатов xpath = '//b[text()="РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ"]' help.f_xpath(browser, xpath) browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") if help.check_no_exists_by_xpath(browser, xpath) == True: print("Тестовый делегат не удален") # заходим в главное меню регламенты - регаламенты href = '[href="#/definitions"]' help.definition(browser, href) xpath = '//b[text()="РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ"]' if help.check_exists_by_xpath(browser, xpath) == True: # Ищем строку РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ line_definition = browser.find_elements_by_css_selector( '[class="text-pointer"]') deleg_definition = browser.find_element_by_xpath( '//b[text()="РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ"]') deleg_definition.click() i = 0 while line_definition[i] != deleg_definition: i += 1 # browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") # удаляем регламент selector = '[class="remove-icon text-black"]' help.f_selectors(browser, selector, i) # подтверждаем удаление alert = WDW(browser, 10).until(EC.alert_is_present()) alert.accept() if help.check_no_exists_by_xpath(browser, xpath) == True: print("Тестовый регламент для делегата не удален") print("Тестовые данные удалены") #test_clean(browser, help)
def renew_ads_in_page(driver, id_list, sleep_time, quiet=False, random_wait=False): """Renew ads from a list containing the full ad IDs. Iteratively renews all ads from the list, following human-like behavior. A sleep time can be supplied to not raise any suspicion. """ # Initialize wait time variable which may change if random_wait is enabled wait_time = sleep_time for id in id_list: id = id.text[1:] # Skip ads that can't be renewed yet if not can_renew(driver, id): if not quiet: logging.info( f"Skipping ad with id {id} since it can't be renewed yet") continue # Get the javascript command for opening the pop-up using only the ID numbers open_popup = f"ventana('renovar/?id=','{id}')" driver.execute_script(open_popup) # Switch to pop-up and click renew link driver.switch_to.frame("ifrw") clickable = driver.find_element_by_id("lren") clickable.click() # Check for any alerts, in case the ad couldn't be renewed # In case there's an alert, close it and the pop-up try: alert = WebDriverWait(driver, 1).until( EC.alert_is_present() ) alert.accept() except Exception: pass # Switch back to parent frame driver.switch_to.default_content() if random_wait: # Randomly increase or decrease up to 10% of the original value wait_time = sleep_time * (0.9 + random() * 0.2) if not quiet: logging.info( f"Ad {id} renewed. Waiting {wait_time:.2f} seconds...") sleep(wait_time)
def test_alert(self): # wait for button to be visible button = WebDriverWait(self.driver, 10).until(ec.visibility_of_element_located((By.ID, "js-btn"))) # click on Clear All link this will display an alert to the user button.click() # wait for the alert to present alert = WebDriverWait(self.driver, 10).until(ec.alert_is_present()) # get the text from alert alert_text = alert.text # check alert text self.assertEqual("Hello! I am an alert box!", alert_text) # click on Ok button alert.accept()
def solve_quiz_and_get_code(self): try: time.sleep(0.2) alert = WebDriverWait(self.browser, 3).until(EC.alert_is_present()) x = alert.text.split(" ")[2] answer = str(math.log(abs((12 * math.sin(float(x)))))) alert.send_keys(answer) alert.accept() time.sleep(0.2) try: alert = WebDriverWait(self.browser, 3).until(EC.alert_is_present()) #print("Your code: {}".format(alert.text)) alert.accept() except NoAlertPresentException: print("No second alert presented") except: pass
def test_compare_product_removal_alert(self): closefirstlogin = self.driver.find_element_by_xpath( "//button[@class='_2AkmmA _29YdH8']") closefirstlogin.click() sleep(2) search_field = self.driver.find_element_by_xpath("//input[@name='q']") search_field.clear() search_field.send_keys('Phones') search_field.submit() sleep(2) self.driver.find_element_by_xpath( "//div[contains(text(),'Redmi Note 5 (Black')]//parent::*//parent::*//parent::*//child::label//div[@class='_1p7h2j']" ).click() sleep(2) clear_all_link = WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located( (By.XPATH, "//span[contains(text(),'COMPARE')]"))) sleep(2) hoveraction1 = ActionChains(self.driver) hoveraction1.move_to_element(clear_all_link) hoveraction1.perform() sleep(5) #clear_all_link.click() closebutton = WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located( (By.XPATH, "//div[@class='_2giIUw']//child::span[@class='_3CbzG3']"))) closebutton.click() sleep(5) alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present()) sleep(15) alert_text = alert.text self.assertEqual( "Are you sure you would like to remove all products from your comparison?", alert_text) alert.accept() def tearDown(self): self.driver.quit()
def setUp(self): self.driver = webdriver.Chrome() self.driver.get("http://demo.magentocommerce.com") search_filed = self.driver.find_element_by_name("q") search_filed.clear() search_filed.send_keys("phones") search_filed.submit() self.driver.find_element_by_link_text("Add to Compare").click() clear_all_link = WebDriverWait(self.driver, 10).\ until(expected_conditions.visibility_of_element_located((By.LINK_TEXT, "Clear All"))) clear_all_link.click() alert = WebDriverWait(self.driver, 10).until(expected_conditions.alert_is_present()) alert_text = alert.text self.assertEqual("Are you sure you would like to remove all products from your comparison?", alert_text) alert.accept()
def testHandleFrame(self): driver = self.driver WebSite = os.path.join(os.path.abspath('..'), 'Html', '10.41', 'frameset.html') driver.get(WebSite) time.sleep(2) #等待2秒 driver.switch_to.frame( 0) #使用switch_to.frame()方法进入框架页面,索引从0开始,从左至右分别是0,1,2 LeftFrameText = driver.find_element_by_xpath('//p') #找到左边框架的文字 self.assertAlmostEqual( LeftFrameText.text, 'This is Left side Frame' ) #assertAlmostEqual断言方法,去判断左侧框架内文字'This is Left side Frame'是否和预期文字一致 driver.find_element_by_tag_name('input').click() #点击左侧框架的按钮 time.sleep(2) try: alertWindow = WebDriverWait(driver, 10).until( EC.alert_is_present() ) #WebDriverWait是设置显式等待的方法,这里设置10秒等待时间,直到alert框弹出 print(alertWindow.text) time.sleep(2) alertWindow.accept() except TimeoutException as e: print(e) driver.switch_to.default_content( ) #使用switch_to_default.content()方法回到默认页,不使用该方法,是无法进入其他frame框架 driver.switch_to.frame( driver.find_elements_by_tag_name('frame')[1]) #进入中间的frame框架 assert 'This is Middle side Frame' in driver.page_source #判断'This is Middle side Frame'是否在当前frame内 driver.find_element_by_tag_name('input').send_keys( 'I am on the middle side frame!') time.sleep(2) driver.switch_to.default_content() driver.switch_to.frame( driver.find_element_by_id('rightframe')) #进入右边的frame框架 assert 'This is Right side Frame' in driver.page_source #判断'This is Right side Frame'是否在当前frame内 time.sleep(2) driver.switch_to.default_content()
def getalert(browser, location=0, size=0): #需要抓图时传入这两个参数, 出现alert时再获得会出错 ## 等待页面完全载入完成 try: wait_for_page_load(browser) except: pass texts="" """ ## 用于类型判断, 适应一些特殊的驱动 (无法判断 htmlunit) types=str(browser) if "phantomjs" in types: pass """ # http://uniquepig.iteye.com/blog/1568197 selenium 可捕获异常类型 timeout=30 ##默认的等待时间 #### 获得 driver 属性 drivertypes = drivertype() if drivertypes ==5 or drivertypes ==15 or drivertypes ==25 : # phantomjs , 容器 htmlunitjs , 远程 htmlunitjs # 需要在操作前提前注入脚本 acceptbyalert_beforedo_ghostdriver(browser) texts=u"GhostDriver模式,未获取" ### 这里是 Phantomjs , Htmlunit (Htmlunitjs) 模式的判断返回 else: try: alert=WebDriverWait(browser, timeout).until(EC.alert_is_present()) #alert=browser.switch_to_alert() ## 某些驱动的版本情况 texts=alert.text ### 截图插入报告 由于没有元素, 所以采用方式2抓图 if location!=0 and size!=0 : insertthepic(browser,location,size) alert.accept() ##进行了选择 except TimeoutException: timeoutlog(browser,xpath, waittime) return(texts)
def _impersonate(self, user): """Impersonate the giver user account where `user` is a guid. Parameters ---------- user : str The guid of the user account to impersonate. """ d = self.d qs = {"id": user, "view": "active"} url = self.base_url + "/manage/database/security/user?" + urlencode(qs) d.get(url) if d.title == "503 Error": raise UserDoesNotExistException(f"{user}: User does not exist.") wait = WebDriverWait(d, 10) wait.until(EC.visibility_of_element_located((By.TAG_NAME, "h1"))) d.find_element_by_link_text("Impersonate").click() alert = WebDriverWait(d, 10).until(EC.alert_is_present()) alert.accept() return self.d
def test_it(self): browser.get(self.login_url) self.assertEqual(browser.title, 'Auth Page') browser.find_element_by_id('yahoo').submit() WebDriverWait(browser, 2).until( EC.presence_of_element_located((By.ID, 'username'))) self.assertEqual(browser.title, 'Sign in to Yahoo!') login = browser.find_element_by_id('username') login.send_keys(self.login) passwd = browser.find_element_by_id('passwd') passwd.send_keys(self.password) passwd.submit() # there may be a captcha here, possibly wait for user input??? find_alert = EC.alert_is_present() find_auth_agree = EC.presence_of_element_located((By.ID, 'agree')) WebDriverWait(browser, 2).until( lambda driver: find_alert(driver) or find_auth_agree(driver)) auth_agree = browser.find_element_by_id('agree') if auth_agree: auth_agree.click() alert = WebDriverWait(browser, 2).until(EC.alert_is_present()) else: alert = browser.switch_to_alert() alert.accept() result = WebDriverWait(browser, 5).until( EC.presence_of_element_located((By.ID, 'result'))) self.assertEqual(browser.title, 'Result Page') result = json.loads(result.text) self.assertTrue('profile' in result) self.assertTrue('credentials' in result) profile = result['profile'] self.assertTrue('displayName' in profile) self.assertTrue('accounts' in profile) self.assertTrue('emails' in profile) creds = result['credentials'] self.assertTrue('oauthAccessToken' in creds) self.assertTrue('oauthAccessTokenSecret' in creds)
def test_js_alert(self): # click the JavaScript Alerts to open test-page self.driver.find_element_by_link_text('JavaScript Alerts').click() # wait for Alert Button to be visible confirm_button = WebDriverWait(self.driver, 10)\ .until(expected_conditions.visibility_of_element_located( (By.XPATH, "//li/button[text()='Click for JS Confirm']"))) # click on Alert Button, # this will display an alert to the user confirm_button.click() # wait for the alert to present alert = WebDriverWait(self.driver, 10)\ .until(expected_conditions.alert_is_present()) # get the text from alert alert_text = alert.text # check alert text self.assertEqual('I am a JS Confirm', alert_text) # click on Ok button alert.accept()
def deleteCourseUploads(tester, debug=True): sysadmin(tester) d = tester.driver d.switch_to.default_content() d.switch_to.frame("contentFrame") d.find_element_by_partial_link_text("Manage Content").click() d.switch_to.default_content() d.switch_to.frame("contentFrame") d.switch_to.frame("WFS_Navigation") WebDriverWait(d, MAX_WAIT).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Tools"))).click() WebDriverWait(d, MAX_WAIT).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Go to Location"))).click() d.switch_to.default_content() d.switch_to.frame("contentFrame") d.switch_to.frame("WFS_Files") Location = WebDriverWait(d, MAX_WAIT).until(EC.presence_of_element_located((By.ID, "entryURL_CSFile"))) Location.click() Location.clear() Location.send_keys("/internal/courses/") d.find_element_by_xpath("//input[@name='top_Submit']").click() if debug: printTitle(d) print "Searching to /internal/courses" WebDriverWait(d, 30).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Edit Paging"))).click() IPP = d.find_element_by_xpath("//input[@id='listContainer_numResults']") IPP.clear() IPP.send_keys("2000") Go = d.find_element_by_xpath("//a[@id='listContainer_gopaging']") Go.click() sortedDesc = False while sortedDesc is False: size = WebDriverWait(d, 10).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Size"))) try: d.find_element_by_xpath("//span[@sortdir='down']") sortedDesc = True break except: size.click() time.sleep(2) irFile = open(tester.course_id_dump, "r") existingCourses = {} for row in irFile: c = row.lstrip().rstrip() existingCourses[c] = True if len(existingCourses) < 10: print "Problem with list of courses" return False if debug: print "Sample course ID: '" + list(existingCourses)[5] + "'" while True: WebDriverWait(d, 300).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Edit Paging"))) time.sleep(2) d.find_element_by_id("listContainer_selectAll").click() time.sleep(4) rows = d.find_element_by_id("listContainer_databody").find_elements_by_tag_name("TR") clicked = len(rows) print "Found " + str(len(rows)) + " rows" for row in rows: courseHREF = row.find_element_by_tag_name("th").find_element_by_tag_name("a") if courseHREF and courseHREF.text: if "20" in courseHREF.text: courseName = courseHREF.text.lstrip().rstrip() if debug: print "Searching for course '" + courseName + "'" if courseName not in existingCourses: if debug: print "Checking course '" + courseName + "'" continue if debug: print "Unchecking course '" + courseName + "'" row.find_element_by_tag_name("input").click() clicked -= 1 print "Will delete " + str(clicked) + " courses" d.find_element_by_partial_link_text("Delete").click() retries = 0 while retries < 3: try: try: deleteAlert = WebDriverWait(d, MAX_WAIT).until(EC.alert_is_present()) except: pass deleteAlert = d.switch_to.alert if deleteAlert: time.sleep(3) # give me time to verify the alert is there deleteAlert.accept() break except Exception as e: print "Failed at alerts" traceback.print_exc() retries += 1 time.sleep(3) if clicked == 0: print "Done" return True time.sleep(30) WebDriverWait(d, 600).until(readystate_complete) print "Deleted " + str(clicked) + " courses" WebDriverWait(d, 300).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Refresh"))).click() return True
def deleteOrphanedContent(tester, debug=True): sysadmin(tester) d = tester.driver d.switch_to.default_content() d.switch_to.frame("contentFrame") d.find_element_by_partial_link_text("Administrator Search").click() d.switch_to.default_content() d.switch_to.frame("contentFrame") WebDriverWait(tester.driver, MAX_WAIT).until( EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Content Orphaned by Location")) ).click() d.switch_to.default_content() d.switch_to.frame("contentFrame") if debug: printTitle(d) print "About to edit paging" WebDriverWait(tester.driver, 300).until( EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Edit Paging")) ).click() # PageButton=d.find_element_by_xpath("//a[text()[contains(.,'Edit Paging')]]") # PageButton.click() IPP = d.find_element_by_xpath("//input[@id='listContainer_numResults']") IPP.clear() IPP.send_keys("1000") Go = d.find_element_by_xpath("//a[@id='listContainer_gopaging']") Go.click() for x in range(0, 10): d.switch_to.default_content() d.switch_to.frame("contentFrame") if debug: printTitle(d) print "Edited paging, waiting for selectAll" WebDriverWait(tester.driver, 600).until( EC.presence_of_element_located((By.ID, "listContainer_selectAll")) ).click() error = None try: error = d.find_element_by_id("badMsg1").text print error except: pass try: if error and "Failure deleting content." in error: delCourseContents(d) except: traceback.print_exc() time.sleep(SHORT_WAIT) try: rows = d.find_element_by_id("listContainer_databody").find_elements_by_tag_name("TR") print str(len(rows)) + " rows" except Exception as e: print "Failed at counting" traceback.print_exc() time.sleep(SHORT_WAIT) if debug: printTitle(d) print "Select All Found" try: d.find_element_by_id("listContainer_row:0") except: print "Done" return False d.find_element_by_partial_link_text("Delete").click() if debug: print "Clicked Delete" time.sleep(SHORT_WAIT) deleteAlert = None try: deleteAlert = WebDriverWait(d, MAX_WAIT).until(EC.alert_is_present()) deleteAlert = tester.driver.switch_to.alert if deleteAlert: deleteAlert.accept() except Exception as e: # print "Failed at alerts" # traceback.print_exc() pass print "Deleted 1000 courses" return True