def move_slider(self, move_x): track = self.simulation_track(move_x - self.error) move_element = self.driver.find_element_by_class_name( 'geetest_slider_button') action = ActionChains(self.driver) action.click_and_hold(move_element).perform() time.sleep(0.3) for i, x in enumerate(track): action.move_by_offset(x, 0).perform() if i < 1 / 3 * len(track): time.sleep(0.01) if i < 1 / 2 * len(track): time.sleep(0.02) elif i < 3 / 4 * len(track): time.sleep(0.04) elif i < 5 / 6 * len(track): time.sleep(0.08) else: time.sleep(0.1) action = ActionChains(self.driver) time.sleep(0.5) action.release().perform() time.sleep(3) try: self.driver.find_element_by_class_name('geetest_slider_button') return 0 except: return 1
def _test_image_transform( self, driver: WebDriver, image_holder: WebElement, left_transform_matrices: List[Tuple[str, str]], right_transform_matrices: List[Tuple[str, str]], ) -> None: main_image_container = driver.find_element_by_id( 'id_main_image_container', ) rotate_left_elem = driver.find_element_by_id('id_rotate_left') for rotation_matrix, translation_matrix in left_transform_matrices: rotate_left_elem.click() transform = image_holder.value_of_css_property('transform') self.assertEqual(rotation_matrix, transform) drag_image = ActionChains(driver) drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=57, yoffset=91, ) drag_image.click_and_hold() drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=107, yoffset=191, ) drag_image.release() drag_image.perform() transform = image_holder.value_of_css_property('transform') self.assertEqual(translation_matrix, transform) rotate_left_elem.click() rotate_right_elem = driver.find_element_by_id('id_rotate_right') for rotation_matrix, translation_matrix in right_transform_matrices: rotate_right_elem.click() transform = image_holder.value_of_css_property('transform') self.assertEqual(rotation_matrix, transform) drag_image = ActionChains(driver) drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=57, yoffset=91, ) drag_image.click_and_hold() drag_image.move_to_element_with_offset( to_element=main_image_container, xoffset=107, yoffset=191, ) drag_image.release() drag_image.perform() transform = image_holder.value_of_css_property('transform') self.assertEqual(translation_matrix, transform) rotate_right_elem.click()
def add_library_item_to_dataflow(self, item_name, instance_name, check=True, offset=None, prefix=None): """ Add component `item_name`, with name `instance_name`. """ library_item = self.get_library_item(item_name) target = WebDriverWait(self.browser, TMO).until( lambda browser: browser.find_element_by_xpath("//*[@id='-dataflow']") ) offset = offset or (90, 90) chain = ActionChains(self.browser) if False: chain.drag_and_drop(library_item, target) else: chain.click_and_hold(library_item) chain.move_to_element_with_offset(target, offset[0], offset[1]) chain.release(None) chain.perform() page = ValuePrompt(self.browser, self.port) page.set_value(instance_name) # Check that the prompt is gone so we can distinguish a prompt problem # from a dataflow update problem. time.sleep(0.25) self.browser.implicitly_wait(1) # We don't expect to find anything. try: eq(len(self.browser.find_elements(*page("prompt")._locator)), 0) finally: self.browser.implicitly_wait(TMO) retval = None if check: # Check that it's been added. retval = WebDriverWait(self.browser, TMO).until( lambda browser: self.get_dataflow_figure(instance_name, prefix) ) return retval
def open_game(gameid, provider): conf = getattr(GameConfigs, provider) driver.get("https://games.vbet.com/authorization.php?partnerId=4&gameId=" + gameid + "&language=en&openType=fun&devicetypeid=1") time.sleep(3) driver.switch_to.frame( driver.find_element_by_xpath('//*[@id="gameFrame"]')) canvas = driver.find_element_by_tag_name('canvas') actions = ActionChains(driver) location = canvas.location size = canvas.size left = location['x'] top = location['y'] right = location['x'] + size['width'] bottom = location['y'] + size['height'] flag = True while flag: png = driver.get_screenshot_as_png() im = Image.open(BytesIO(png)) im = im.crop((left, 50, right, 100)) # defines crop points im.save('current.png') # saves new cropped image if not is_equal('screenshot.png', 'current.png'): flag = False print "load ended" for k in conf[gameid]: x_offset = k[0] y_offset = k[1] actions.move_to_element_with_offset(canvas, x_offset, y_offset) actions.click_and_hold() actions.release() actions.perform() time.sleep(2)
def test1(): driver = webdriver.Chrome(r"F:\automation_git\FormTalk\WebTEST\main\drivers\chromedriver.exe") driver.get("https://testpro.formtalk.net/login.do") driver.maximize_window() driver.find_element_by_css_selector("input[name=loginName]").send_keys("17111111111") time.sleep(1) driver.find_element_by_css_selector('input[name=loginPassword]').send_keys("123456") time.sleep(1) action = ActionChains(driver) SliderVerifyCodeIcon = driver.find_element_by_css_selector("span.verifyCode-icon") action.drag_and_drop_by_offset(SliderVerifyCodeIcon, driver.find_element_by_css_selector(("span.labelTip")).size["width"], 0).perform() action.release().perform() action.move_to_element(SliderVerifyCodeIcon).release() """登录""" time.sleep(1) driver.find_element_by_css_selector('input#doLogin').click() time.sleep(10) driver.switch_to.default_content() driver.find_element_by_css_selector("div[title=自动化应用准备1_新版]").click() time.sleep(2) driver.switch_to.frame(driver.find_element_by_css_selector("#iframeUseApp")) driver.switch_to.frame(driver.find_element_by_css_selector("#app-main-iframe")) driver.find_element_by_css_selector("button.form-udata-add-span.btns-info").click() driver.switch_to.window(driver.window_handles[-1]) driver.switch_to.window(driver.window_handles[0]) print("切换成功") time.sleep(15)
def set_range(driver, el,): ac = ActionChains(driver) ac.move_to_element(el) ac.click_and_hold() ac.move_by_offset(0, 50) ac.release() ac.perform()
def _test_reorder_file_bar(self, page): page.add_file([x for x in FILES if x.name == 'test.jpg'][0]) WebDriverWait(page.driver, 3).until( ec.visibility_of_element_located( ( By.CSS_SELECTOR, 'div.grid-canvas div.ui-widget-content.slick-row.odd' ) ) ) ac = ActionChains(page.driver) a = page.driver.find_elements_by_css_selector( 'DIV.container DIV.slick-header.ui-state-default DIV.slick-header-columns.ui-sortable SPAN.slick-column-name' )[3] b = page.driver.find_elements_by_css_selector( 'DIV.container DIV.slick-header.ui-state-default DIV.slick-header-columns.ui-sortable SPAN.slick-column-name' )[0] ac.click_and_hold(a).perform() a_chain = ActionChains(page.driver) a_chain.move_to_element(b).perform() a_chain.release(b).perform() downloads = page.driver.find_element_by_css_selector( 'div.grid-canvas div.ui-widget-content.slick-row.odd DIV.slick-cell.l0.r0' ).text self.assertIn('0', downloads) page.close()
def move2(self, browser): """ complete actions of sliding captcha """ self.save_img(browser) self.calc_position(browser) offset = self.get_offset('./captcha/template1.jpg', './captcha/template2.jpg') print("offset calc by get_offset() is: {}".format(offset)) tracks = self.get_tracks(offset) print("the track array is: {}".format(tracks)) slider = browser.find_element_by_class_name("JDJRV-slide-btn") action = ActionChains(browser) action.click_and_hold(slider).perform() action.reset_actions() for i in tracks: action.move_by_offset(round(i), 0).perform() print('should move--<{}>--'.format(i)) print('moving--<{}>--'.format(slider.location['x'])) time.sleep(0.1) # in order to prevent accumulation actions action.reset_actions() # useful # action = ActionChains(browser) # useful time.sleep(4) action.release().perform()
def view_tour(self, where, number): number = number * 2 for i in range(number): time.sleep(2) moveForX = int(int(self.tourImage().size["width"]) / 8) moveForY = int(int(self.tourImage().size["height"]) / 8) ac = ActionChains(self.driver) if not self._check_hotSpot_on_view(): ac.move_to_element(self.tourImage()) else: if i == 0: ac.move_to_element(self.tourImage()) hs_loc = self.where_to_move_edit_and_view() if where == "right": ac.move_by_offset(-1 * hs_loc[0], 0) elif where == "left": ac.move_by_offset(hs_loc[1], 0) else: break ac.click_and_hold() if where == "right": ac.move_by_offset(moveForX * -1, 0) elif where == "left": ac.move_by_offset(moveForX, 0) elif where == "up": ac.move_by_offset(0, moveForY * -1) elif where == "down": ac.move_by_offset(0, moveForY) ac.release() try: ac.perform() except: pass time.sleep(2)
def ReleaseClick(cls): ''' 释放按压操作 ''' element = cls._element() action = ActionChains(Web.driver) action.release(element) action.perform()
def move(dis): action = ActionChains(driver) action.click_and_hold(driver.find_element_by_css_selector("div.geetest_slider_button")) trace_list = get_trace_list(dis) for i in trace_list: action.move_by_offset(i, 0) action.release().perform()
def half_rotate(self): ac = ActionChains(self.driver) ac.move_to_element(self.tourImage()) ac.click_and_hold() ac.move_by_offset(self.tourImage().size["width"] / 2, 0) ac.release() ac.perform()
def slide_discern(): print("滑块验证码验证中。。。") # try: # 获取到需滑动的按钮 source = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]') action = ActionChains(driver) # 按住左键不放 action.click_and_hold(source).perform() # 开始滑动 distance = 348 # 模拟以人为速度拖动 track = get_track(distance) # ttt = [23, 81, 224] for i in track: try: action.move_by_offset(xoffset=i, yoffset=0).perform() # perform --- 执行所有准备好的Action # action.reset_actions() # reset_actions --- 清空所有准备好的Action,这个需要selenium版本3.0以上 # time.sleep(0.4) except StaleElementReferenceException as e: action.release().perform() # 释放鼠标 driver.find_element_by_xpath('//div[@class="errloading"]/span/a').click() source = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]') # 获取到需滑动的按钮 action = ActionChains(driver) action.click_and_hold(source).perform() # 按住左键不放 # action.reset_actions() # 清除之前的action action.move_by_offset(xoffset=i, yoffset=0).perform() # perform --- 执行所有准备好的Action # 释放鼠标 action.release().perform()
def drag(self, x_offset, y_offset): center = self.driver.execute_script(GetScripts.getContainerCenter) actions = ActionChains(self.driver) actions.move_to_element_with_offset(self.element, int(center['x']), int(center['y'])) actions.click_and_hold() actions.move_by_offset(x_offset, y_offset) actions.release().perform()
def slider_verification_code_163yidun(browser, cut_element, back_element, slider_element): while True: # 将验证码的背景图和滑块图片下载下来 download_img_by_src(browser, back_element, 'back.jpg') download_img_by_src(browser, cut_element, 'cut.png') sleep(1) cut_image, back_image = read_img_file('cut.png', 'back.jpg') distance = get_distance(back_img=back_image, cut_img=cut_image) print(distance) if distance: action = ActionChains(browser) action.click_and_hold( browser.find_element(slider_element[0], slider_element[1])).perform() # tracks = get_track(distance) # for i in tracks: action.move_by_offset(xoffset=distance, yoffset=-1).perform() action = ActionChains(browser) sleep(1) action.release().perform() sleep(5) if re.findall("订单", browser.page_source, re.S): break if '失败过多,点此重试' in browser.page_source: browser.find_element_by_xpath( "//span[@class='yidun_tips__text']").click()
def do_login(driver, name_pwd): print('=====do_login=====') # 切换到账号登录tab driver.find_element_by_xpath( '/html/body/div[2]/div/div/div[1]/a[2]').click() driver.find_element_by_id('userName').send_keys(name_pwd[0]) driver.find_element_by_id('password').send_keys(name_pwd[1]) # 获取活动模块 button = driver.find_element_by_xpath( '//*[@id="siller1_dt_child_content_containor"]/div[3]') action = ActionChains(driver) action.click_and_hold(button).perform() # 滑动模块 x = 0 while True: action.move_by_offset(xoffset=x, yoffset=0).perform() x += 50 print(x) if x >= 274: break time.sleep(1) action.release().perform() # 点击登录按钮 driver.find_element_by_xpath('//*[@id="submit"]').click() time.sleep(2)
def _add_button_to_center_firefox(self, hotSpot): """ Puts hotSpot or info in center of scene. :param hotSpot: True if hotSpot is added, False if info is added :type hotSpot: bool """ self.log.info("Execute method _add_button_to_center") if hotSpot: button = self.btnHotSpot else: button = self.btnInfo scroll_element_to_center(self.driver, self.log, button()) buttonSize = button().size ac = ActionChains(self.driver) time.sleep(3) ac.move_to_element_with_offset(button(), buttonSize["width"] / 2, buttonSize["height"] / 2).perform() time.sleep(3) ac.click_and_hold().perform() tourSize = self.tourImage().size time.sleep(3) #scroll_element_to_viewPoint_with_selenium(self.driver, self.tourImage()) scroll_element_to_viewpoint_top(self.log, self.driver, self.tourImage()) time.sleep(1) move_mouse_to_middle_of_browser(self.log, self.driver) time.sleep(1) ac.move_to_element_with_offset(self.tourImage(), tourSize["width"] / 2, tourSize["height"] / 2).perform() ac.release().perform() time.sleep(1) self.log.screenshot("Button is added")
def test_1486(self): """ Module登记-正确输入各个输入项 :return: """ self.driver.get('http://222.29.77.148:8205/pages/login.html') self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div/div/input[1]').send_keys('administrator') self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div/div/input[2]').send_keys('letmein') action = ActionChains(self.driver) action.click_and_hold(self.driver.find_element_by_xpath('//*[@id="mpanel1"]/div/div/div/i')).perform() action.move_by_offset(273, 0).perform() action.release().perform() #点击登录 self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div/div/button').click() time.sleep(3) #点击app业务管理 self.driver.find_element_by_xpath('//*[@id="seconde-header-nav"]/li[2]').click() #点击module管理 self.driver.find_element_by_xpath('//*[@id="sidebar"]/ul[2]/ul/li[1]/a/span[1]').click() #点击module登记 //*[@id="sidebar"]/ul[2]/ul/li[1]/a/span[1] self.driver.find_element_by_xpath('//*[@id="67e84f93-e164-4670-99b7-e6aa29713642"]/a').click() #切换到frame self.driver.switch_to.frame(self.driver.find_element_by_xpath('//*[@id="content-main"]/iframe[2]')) # allure.attach(self.driver.save_screenshot(os.getcwd() + "\\" + "images\\" + str(uuid.uuid1()).replace("-", "") + ".png"), "报错页面", allure.attachment_type.PNG) self.driver.find_element_by_xpath('//*[@id="name"]').send_keys('appman') #退出iframe self.driver.switch_to.default_content() print("ok---200")
class SliderCaptcha(object): """滑块验证码""" def __init__(self): self.url = "http://www.porters.vip/captcha/sliders.html" self.driver_path = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe" self.browser = webdriver.Chrome(executable_path=self.driver_path) self.wait = WebDriverWait(self.browser, timeout=20) self.action_chains = ActionChains(self.browser) def __str__(self): self.browser.close() def run(self): self.browser.get(url=self.url) time.sleep(1) # 获取滑块元素对象 # hover = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, "hover"))) # 通过类选择器来定位滑块元素 hover = self.wait.until(EC.presence_of_element_located((By.ID, "sliderblock"))) # 模拟人为拖动滑块 # 通过分析CSS样式得出滑块需要滑动的轨迹为340px self.action_chains.click_and_hold(hover).perform() # 点击并按住滑块不松手 self.action_chains.move_by_offset(340, 0) # 设置滑块轨迹, 模拟滑块横向滑动340px,纵向滑块滑动距离为0px self.action_chains.release().perform() # 松快鼠标 time.sleep(5)
def click_hold(desktop_session: WebDriver, element: WebElement): """ click with click, hold and release method. Added to fix intermittent issue of button click on AWS machine. """ actions = ActionChains(desktop_session) actions.move_to_element(element) actions.click_and_hold(element).perform() actions.release(element).perform()
def select_add_button_with_mouse(self): time.sleep(3) addbtn = self.driver.find_element_by_xpath(self.button_add_xpath) actions = ActionChains(self.driver) actions.move_to_element(addbtn).click_and_hold(addbtn).perform() time.sleep(1) actions.release().perform() print("Add button selected with mouse ") self.logger.info("**************** Add button selected with mouse ****************")
def select_users_Link_with_mouse(self): time.sleep(5) users_link = self.driver.find_element_by_link_text(self.lnk_Users_linktext) actions = ActionChains(self.driver) actions.move_to_element(users_link).click_and_hold(users_link).perform() time.sleep(1) actions.release().perform() print("Users link selected with mouse ") self.logger.info("**************** Users link selected with mouse ****************")
def __clickOnPlaceholderNewMDOption(self): placeholderOpt = self._waitForClickableId( 'itemMachineDesignListForm:machineDesignAddOptions:0') action = ActionChains(self.driver) action.move_to_element(placeholderOpt) action.pause(0.5) action.click() action.release() action.perform()
class taobao(): def __init__(self): self.browser = webdriver.Chrome("chromedriver.exe") # 最大化窗口 self.browser.maximize_window() self.browser.implicitly_wait(5) self.domain = 'https://www.taobao.com/' self.action_chains = ActionChains(self.browser) def login(self, username, password): while True: self.browser.get(self.domain) time.sleep(1) #会xpath可以简化这几步 #self.browser.find_element_by_class_name('h').click() #self.browser.find_element_by_id('fm-login-id').send_keys(username) #self.browser.find_element_by_id('fm-login-password').send_keys(password) self.browser.find_element_by_xpath('//*[@id="J_SiteNavLogin"]/div[1]/div[1]/a[1]').click() self.browser.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys(username) self.browser.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys(password) time.sleep(1) try: # 出现验证码,滑动验证 slider = self.browser.find_element_by_xpath("//span[contains(@class, 'btn_slide')]") if slider.is_displayed(): # 拖拽滑块 self.action_chains.drag_and_drop_by_offset(slider, 258, 0).perform() time.sleep(0.5) # 释放滑块,相当于点击拖拽之后的释放鼠标 self.action_chains.release().perform() except (NoSuchElementException, WebDriverException): logger.info('未出现登录验证码') # 会xpath可以简化点击登陆按钮,但都无法登录,需要使用 pyautogui 完成点击事件 #self.browser.find_element_by_class_name('password-login').click() #self.browser.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click() # 图片地址 coords = pyautogui.locateOnScreen('1.png', confidence=0.5) x, y = pyautogui.center(coords) click = pyautogui.leftClick(x, y) # nickname = self.get_nickname() # if nickname: # logger.info('登录成功,呢称为:' + nickname) # break # logger.debug('登录出错,5s后继续登录') # time.sleep(5) def get_nickname(self): self.browser.get(self.domain) time.sleep(0.5) try: return self.browser.find_element_by_class_name('site-nav-user').text except NoSuchElementException: return ''
def zoom_selection(self): center = self.driver.execute_script(GetScripts.getContainerCenter) actions = ActionChains(self.driver) actions.move_to_element_with_offset(self.element, int(center['x']), int(center['y'])) actions.key_down(Keys.SHIFT) actions.click_and_hold() actions.move_by_offset(300, 300) actions.release() actions.perform()
def login(name, pwd): browser.get("https://login.taobao.com/member/login.jhtml") time.sleep(1) browser.find_element_by_class_name("login-switch").click() time.sleep(1) browser.find_element_by_name("TPL_username").click() time.sleep(1) browser.find_element_by_name("TPL_username").send_keys(name) time.sleep(1) browser.find_element_by_name("TPL_password").click() time.sleep(1) browser.find_element_by_name("TPL_password").send_keys(pwd) time.sleep(1) ishide = str( browser.find_element_by_id("nocaptcha").get_attribute("style")) print(ishide) if ishide == "display: block;": print("move") mm = browser.find_element_by_id("nocaptcha") draggable = browser.find_element_by_id("nc_1_n1z") act = ActionChains(browser) act.click_and_hold(draggable).move_by_offset(270, 0).perform() act.release() print("over") time.sleep(3) browser.switch_to.default_content() try: tt = browser.find_element_by_xpath( "//span[@class='nc-lang-cnt']").text print(tt) if tt == "验证通过": browser.find_element_by_id("J_SubmitStatic").click() time.sleep(3) browser.switch_to.default_content() try: browser.switch_to.frame(0) browser.find_element_by_xpath( "//ul[@class='check-list']/li[1]").click() browser.find_element_by_id("J_Form").submit() time.sleep(3) except selenium.common.exceptions.NoSuchElementException: print("没有点击最近购买验证") else: try: sys.exit(0) except TimeoutError: print('die') finally: print('out') except selenium.common.exceptions.NoSuchElementException: print("no such element") else: browser.find_element_by_id("J_SubmitStatic").click() time.sleep(3)
def mouse_left_click(locatorMethod, locatorExpression, *args): u"""模拟鼠标左键点击操作""" global driver try: action_chains = ActionChains(driver) element = getElement(driver, locatorMethod, locatorExpression) action_chains.click_and_hold(element).perform() action_chains.release(element).perform() except Exception, e: raise e
def normal_drag(dis): # 滑块验证 /html/body/div[4]/div/div/div/div[2]/div[3] slider = chrome.find_element_by_xpath("/html/body/div[4]/div/div/div/div[2]/div[3]") # slider=chrome.find_element_by_class_name(r"JDJRV-slide-inner JDJRV-slide-btn")# 找到“蓝色滑块” action = ActionChains(chrome) # 实例化一个action对象 action.click_and_hold(slider).perform() # perform()用来执行ActionChains中存储的行为 action.reset_actions() action.move_by_offset(dis*0.7714, 0).perform() # 移动滑块 action.release().perform()
def ReleaseClick(cls): #p_log.step_info("normal","Element [%s]: Do ReleaseClick()" % (cls.__name__)) element = cls.__wait() action = ActionChains(p_env.BROWSER) action.release(element) action.perform() cls.__clearup()
def add_library_item_to_dataflow(self, item_name, instance_name, check=True, offset=None, prefix=None, args=None): """ Add component `item_name`, with name `instance_name`. """ offset = offset or (90, 90) xpath = "//*[@id='-dataflow']" library_item = self.get_library_item(item_name) target = WebDriverWait(self.browser, TMO).until( lambda browser: browser.find_element_by_xpath(xpath)) for retry in range(3): try: chain = ActionChains(self.browser) if False: chain.drag_and_drop(library_item, target) else: chain.click_and_hold(library_item) chain.move_to_element_with_offset(target, offset[0], offset[1]) chain.release(None) chain.perform() except StaleElementReferenceException: if retry < 2: logging.warning('add_library_item_to_dataflow:' ' StaleElementReferenceException') library_item = self.get_library_item(item_name) target = WebDriverWait(self.browser, TMO).until( lambda browser: browser.find_element_by_xpath(xpath)) else: raise else: break page = ArgsPrompt(self.browser, self.port) page.set_name(instance_name) if args is not None: for i, arg in enumerate(args): page.set_argument(i, arg) page.click_ok() # Check that the prompt is gone so we can distinguish a prompt problem # from a dataflow update problem. time.sleep(0.25) self.browser.implicitly_wait(1) # We don't expect to find anything. try: eq(len(self.browser.find_elements(*page('prompt')._locator)), 0) finally: self.browser.implicitly_wait(TMO) retval = None if check: # Check that it's been added. retval = WebDriverWait(self.browser, TMO).until( lambda browser: self.get_dataflow_figure(instance_name, prefix)) return retval
def rotate(self, right, clickNumber, useArrows): """ Rotate scene to right or left clickNumber of times. :param right: True for moving to right, False for moving to left :type right: bool :param clickNumber: Number of times to click on arrow :type clickNumber: int """ wait_until(self.btnLeftRotate) self.log.info( "Execute method rotate with parameters right={}, clickNumber={}". format(right, clickNumber)) if clickNumber != 0: if not useArrows: if DriverData.driverName == "Chrome" and DriverData.mobile is False: for i in range(clickNumber): time.sleep(5) # move_to_element_chrome(self.driver, self.tourImage(), 100) pyautogui.mouseDown() #moveFor = int(int(self.tourImage().size["width"]) / 58) moveFor = int(int(self.tourImage().size["width"]) / 8) if right: pyautogui.moveRel(moveFor * -1, 0, 1) else: pyautogui.moveRel(moveFor, 0, 1) pyautogui.mouseUp() time.sleep(5) else: for i in range(clickNumber): time.sleep(5) ac = ActionChains(self.driver) ac.move_to_element(self.tourImage()) ac.click_and_hold() #moveFor = int(int(self.tourImage().size["width"])/58) moveFor = int(int(self.tourImage().size["width"]) / 8) if right: ac.move_by_offset(moveFor * -1, 0) else: ac.move_by_offset(moveFor, 0) ac.release() ac.perform() time.sleep(5) else: if right: button = self.btnRighRotate else: button = self.btnLeftRotate for i in range(clickNumber): time.sleep(1.5) wait_until(lambda: check_if_elem_exist(button), timeout=10) button().click() time.sleep(1.5) self.log.screenshot("Rotate is done")
def scrolling_scr(self): driver = self.driver scr = self.scroll_controller() action_sct = ActionChains(driver) action = ActionChains.move_by_offset(0, 5000).perform() if scr > action: ActionChains.release() elif scr == action_sct: ActionChains.release()
def action_elements_events(self, element_menu, drag_divs): action = ActionChains(self.driver) action.move_to_element(element_menu).click(element_menu) action.click_and_hold(drag_divs) action.move_by_offset(35, 35) action.move_by_offset(15, 20) action.move_by_offset(55, 15) action.release() action.perform() event_start = self.driver.find_element_by_xpath("//li[@id = 'event-start']/span[2]").text event_drag = self.driver.find_element_by_xpath("//li[@id='event-drag']/span[2]").text event_stop = self.driver.find_element_by_xpath("//li[@id = 'event-stop']/span[2]").text return event_start, event_drag, event_stop
def get_column_cursor(step, column_name): with AssertContextManager(step): cursor_css = "body.ember-application" action_chains = ActionChains(world.browser) element = world.browser.execute_script( "return $('.ember-table-header-container .ember-table-content:contains(" + column_name + ")').parent().parent().children()[1]") action_chains.drag_and_drop_by_offset(element, 10, 0).release().perform() cursor = find_elements_by_css(world.browser, cursor_css) style = cursor[0].get_attribute("style") assert_true(step, ("auto" in style) or ("resize" in style) or ("pointer" in style)) action_chains.release() world.browser.refresh()
def connect(self, src, dst): """ Return :class:`ConnectionsPage` for connecting `src` to `dst`. """ chain = ActionChains(self.browser) chain.click_and_hold(src.output_port) # Using root rather than input_port since for some reason # even using a negative Y offset can select the parent's input. chain.move_to_element(dst.input_port) chain.release(None) chain.perform() parent, dot, srcname = src.pathname.rpartition(".") parent, dot, dstname = dst.pathname.rpartition(".") editor_id = "ConnectionsFrame-%s" % (parent) editor_id = editor_id.replace(".", "-") return ConnectionsPage(self.browser, self.port, (By.ID, editor_id))
def editor_page(self, double_click=True, base_type='Component', version=ComponentPage.Version.OLD): """ Return :class:`ComponentPage` for this component. """ chain = ActionChains(self.browser) if double_click: chain.double_click(self.root).perform() else: self._context_click('edit_button') editor_id = 'ObjectFrame_%s' % self.pathname.replace('.', '-') chain.release(None).perform() if base_type == 'Assembly': return AssemblyPage(self.browser, self.port, (By.ID, editor_id)) elif base_type == 'Driver': return DriverPage(self.browser, self.port, (By.ID, editor_id)) else: return ComponentPage(self.browser, self.port, (By.ID, editor_id), version=version)
def replace(self, name, classname, confirm=True): """ Replace `name` with an instance of `classname`. """ library_item = self.get_library_item(classname) target = self.get_dataflow_figure(name).root chain = ActionChains(self.browser) chain.click_and_hold(library_item) chain.move_to_element_with_offset(target, 125, 30) chain.release(None) chain.perform() dialog = ConfirmationPage(self) if confirm: dialog.click_ok() else: dialog.click_cancel()
def add_object_to_workflow(self, obj_path, target_name): """ Add `obj_path` object to `target_name` in workflow. """ for retry in range(3): try: obj = self.find_object_button(obj_path) target = self.get_workflow_figure(target_name) chain = ActionChains(self.browser) chain.move_to_element(obj) chain.click_and_hold(obj) chain.move_to_element(target.root) chain.move_by_offset(2, 1) chain.release(None) chain.perform() except StaleElementReferenceException: if retry < 2: logging.warning("add_object_to_workflow:" " StaleElementReferenceException") else: raise else: break
def _add_device(self, port, device_type_id): browser = self._browser test_bed = browser.find_element_by_id('test-bed') device = browser.find_element_by_id(device_type_id) # drag action_chains = ActionChains(browser) action_chains.click_and_hold(device) action_chains.move_to_element(test_bed).perform() time.sleep(1) # drop drop_hw = browser.find_element_by_class_name('drop-hw') action_chains = ActionChains(browser) action_chains.move_to_element(drop_hw) action_chains.release(drop_hw).perform() time.sleep(0.5) selected_hw = browser.find_element_by_class_name('selected-hw') form_inputs = selected_hw.find_elements_by_tag_name('input') form_port = form_inputs[0] form_port.clear() form_port.send_keys(port)
def setUpClass(cls): super(ReorderComponentTest, cls).setUpClass() cls.project_url = cls.page.driver.current_url cls.page.add_component( title='first', component_type='hypothesis', ) cls.page.driver.get(cls.project_url) cls.page.add_component( title='second', component_type='hypothesis', ) cls.title = cls.page.title cls.page.driver.get(cls.project_url) # Second method: by element ac = ActionChains(cls.page.driver) a = cls.page.driver.find_element_by_css_selector('#Nodes li:first-child') b = cls.page.driver.find_element_by_css_selector('#Nodes li:last-child') ac.click_and_hold(a).perform() a_chain = ActionChains(cls.page.driver) a_chain.move_to_element(b).perform() a_chain.release(b).perform()
def fill_slot_from_library(self, slot, classname, args=None): """ Fill slot with `classname` instance from library. """ for retry in range(3): try: button = self.find_library_button(classname) chain = ActionChains(self.browser) chain.move_to_element(button) chain.click_and_hold(button) chain.move_to_element(slot.root) chain.release(None) chain.perform() except StaleElementReferenceException: if retry < 2: logging.warning('fill_slot_from_library:' 'StaleElementReferenceException') else: raise else: break # Handle arguments for the slotted class page = ArgsPrompt(self.browser, self.port) argc = page.argument_count() if argc > 0: if args is not None: for i, arg in enumerate(args): page.set_argument(i, arg) page.click_ok() # Check that the prompt is gone so we can distinguish a prompt problem # from a dataflow update problem. time.sleep(0.5) self.browser.implicitly_wait(1) # We don't expect to find anything. try: eq(len(self.browser.find_elements(*page('prompt')._locator)), 0) finally: self.browser.implicitly_wait(TMO)
def interact_mouse( self ): ''' Perform some mouse interaction in the current active browser window. ''' canvas = self.__browser.find_element_by_tag_name( 'canvas' ) canvas_width = canvas.get_attribute('width') canvas_height = canvas.get_attribute('height') # move to canvas center to trigger a caption actions = ActionChains( self.__browser ) actions.click( canvas ) actions.move_to_element_with_offset( canvas, int(canvas_width)/2, int(canvas_height)/2 ) actions.perform() time.sleep(3) # # rotate, pan, zoom # actions = ActionChains( self.__browser ) actions.click( canvas ) # rotate for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 10, 0 ); actions.release( canvas ) for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, -10 ); actions.release( canvas ) # zoom (not possible right now since the scrollwheel can't be triggered) # pan for i in range( 10 ): actions.key_down( Keys.LEFT_SHIFT ) actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, 10 ); actions.release( canvas ) actions.perform()
def test_drag_drop(self): print "Reorder site test is commencing." wait = WebDriverWait(self.driver, self.waitTime) self.driver.get(self.url) print "Starting logging in." wait.until(EC.element_to_be_clickable((By.ID, 'login-button'))).click() wait.until( EC.element_to_be_clickable((By.ID, 'weebly-username'))).click() wait.until( EC.element_to_be_clickable((By.ID, 'weebly-password'))).click() Username = self.driver.find_element_by_id('weebly-username') Username.send_keys(self.email) Password = self.driver.find_element_by_id('weebly-password') Password.send_keys(self.password) wait.until(EC.element_to_be_clickable( (By.XPATH, "//form[@id='weebly-login']/p[4]/input"))).click() print "Selecting Store to edit." wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Jon's Site"))) self.driver.find_element_by_link_text("Jon's Site").click() print "Make sure drag and drop elements exist before starting drag and drop." try: self.assertTrue(self.is_element_present(By.XPATH, "//li[2]/div[2]/div/div")) except AssertionError as e: self.verificationErrors.append(str(e)) try: self.assertTrue(self.is_element_present(By.XPATH, "//div[2]/div/h2")) except AssertionError as e: self.verificationErrors.append(str(e)) print "Elements exist. Get first item on lists location." hover_element1 = self.driver.find_element_by_xpath("//div[2]/div/h2") hover_action1 = ActionChains(self.driver) hover_action1.move_to_element(hover_element1).perform() time.sleep(4) print "Drag and drop the second item on the list to the first items location." hover_element2 = self.driver.find_element_by_xpath("//li[2]/div[2]/div/div") hover_action2 = ActionChains(self.driver) hover_action2.move_to_element(hover_element2).perform() time.sleep(4) drag_second_spot = self.driver.find_element_by_xpath("//li[2]/div/div[2]/div") drag_first_spot = self.driver.find_element_by_xpath("//div[2]/div/h2") locate = self.driver.find_element_by_id('secondlistParent') drag_item = ActionChains(self.driver) drag_item.click_and_hold(drag_second_spot) drag_item.move_to_element_with_offset(drag_first_spot, 1, 1) drag_item.release(on_element=None) drag_item.perform() time.sleep(10) print "Drag and drop should now be complete." print "Exit the editor." wait.until(EC.element_to_be_clickable( (By.XPATH, "//li[@id='more-drop-button']/a/span"))).click() wait.until(EC.element_to_be_clickable( (By.LINK_TEXT, "Exit Editor"))).click() print "Exited the editor" print "Log out" wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Logout")) ).click() print "Logged out!"
def runTests( xtkTestFile, xtkLibDir, browserString ): print 'RUNNING OFFSCREEN TESTING..' browser = getBrowser( xtkLibDir, browserString ) if not browser: return None if xtkTestFile.find( 'build' ) == -1: # this is against the DEV tree # start coverage server coverageServer( xtkLibDir ) browser.get( "http://localhost:8080/jscoverage.html" ) # now some selenium fun locationfield = browser.find_element_by_id( 'location' ) locationfield.clear() # fill in url actions = ActionChains( browser ) actions.click( locationfield ) actions.send_keys( 'testing/xtk_tests.html' ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.RETURN ) actions.perform() browser.switch_to_window( browser.window_handles[-1] ) #browser.switch_to_frame( browser.find_elements_by_tag_name( "iframe" )[0] ) else: # we don't need os.sep here since it's a url browser.get( "file://" + xtkTestFile ) time.sleep( 3 ) result_unit = browser.execute_script( 'return window.G_testRunner.getReport(true);' ) time.sleep( 1 ) browser.switch_to_window( browser.window_handles[0] ) #browser.close() print 'RUNNING OFFSCREEN TESTING.. DONE!' # if xtkTestFile.find( 'build' ) == -1: # this is against the DEV tree # stop coverage server #coverageServer( xtkLibDir, 'stop' ) #return result #def testVisualization( xtkLibDir, browserString, againstBuild=False ): print 'RUNNING VISUAL TESTING..' #browser = getBrowser( xtkLibDir, browserString ) if not browser: return None # list of tests tests = ['test_trk.html', 'test_vtk.html', 'test_nrrd.html', 'test_vr.html', 'test_labelmap.html', 'test_shapes.html', 'test_mgh.html', 'test_mgz.html', 'test_stl.html', 'test_binstl.html'] #testURL = "file://" + xtkLibDir + "/../testing/visualization/" testURL = "testing/visualization/" baselineDir = os.path.abspath( xtkLibDir + "/../testing/visualization/baselines/" ) # we test the visualization with a fixed window size browser.set_window_size( 800, 600 ) output = '' # loop through the tests for t in tests: # open the test url = testURL + t #if againstBuild: # url += '?build' #browser.get( testURL + t ) browser.switch_to_default_content() # now some selenium fun locationfield = browser.find_element_by_id( 'location' ) locationfield.clear() # fill in url actions = ActionChains( browser ) actions.click( locationfield ) actions.send_keys( url ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.RETURN ) actions.perform() browser.switch_to_window( browser.window_handles[-1] ) #browser.switch_to_frame( browser.find_elements_by_tag_name( "iframe" )[0] ) # wait until loading fully completed timer = 0 while not browser.execute_script( 'return test_renderer.loadingCompleted' ) and timer < 5: time.sleep( 1 ) # loading did not complete yet timer += 1 time.sleep( 1 ) # perform interaction tests, if we are using chrome if browserString == 'chrome': canvas = browser.find_element_by_tag_name( 'canvas' ) actions = ActionChains( browser ) actions.click( canvas ) # # keyboard events # # rotate for i in range( 30 ): actions.send_keys( Keys.ARROW_RIGHT ) for i in range( 30 ): actions.send_keys( Keys.ARROW_UP ) for i in range( 30 ): actions.send_keys( Keys.ARROW_LEFT ) for i in range( 30 ): actions.send_keys( Keys.ARROW_DOWN ) # zoom for i in range( 50 ): actions.key_down( Keys.LEFT_ALT ) actions.send_keys( Keys.ARROW_LEFT ) for i in range( 25 ): actions.key_down( Keys.LEFT_ALT ) actions.send_keys( Keys.ARROW_RIGHT ) # pan actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_RIGHT, Keys.ARROW_RIGHT, Keys.ARROW_RIGHT ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_LEFT, Keys.ARROW_LEFT, Keys.ARROW_LEFT ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_UP, Keys.ARROW_UP, Keys.ARROW_UP ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_DOWN, Keys.ARROW_DOWN ) # # mouse # actions.click( canvas ) # rotate for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 10, 0 ); actions.release( canvas ) for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, -10 ); actions.release( canvas ) # zoom # pan for i in range( 10 ): actions.key_down( Keys.LEFT_SHIFT ) actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, 10 ); actions.release( canvas ) actions.perform() # create a screenshot and save it to a temp. file testId = os.path.splitext( t )[0] testFileId = testId + '_' + browserString tmpfile = tempfile.mkstemp( suffix='.png', prefix='xtk_' + testFileId )[1] browser.save_screenshot( tmpfile ) # baseline baseline = os.path.join( baselineDir, testFileId + '_baseline.png' ) # compare temp. file vs. baseline testPassed = compareImages( tmpfile, baseline ) _now = datetime.now() timestamp = str( _now.hour ).zfill( 2 ) + ':' + str( _now.minute ).zfill( 2 ) + ':' + str( _now.second ).zfill( 2 ) + '.' + str( _now.microsecond / 1000 ).zfill( 3 ) if testPassed: testPassed = "PASSED : " + tmpfile + " : " + baseline + " : " else: testPassed = "FAILED : " + tmpfile + " : " + baseline + " : " testPassed += "\n" + timestamp + " ERROR in Visualization" + testId + '\nComparison against baseline failed.\n' output += timestamp + " Visualization" + testId + ' : ' + testPassed + '\n' browser.switch_to_window( browser.window_handles[0] ) #browser.close() _now = datetime.now() timestamp = str( _now.hour ).zfill( 2 ) + ':' + str( _now.minute ).zfill( 2 ) + ':' + str( _now.second ).zfill( 2 ) + '.' + str( _now.microsecond / 1000 ).zfill( 3 ) result = output + timestamp + ' Done\n' print output print 'RUNNING VISUAL TESTING.. DONE!' browser.switch_to_window( browser.window_handles[0] ) browser.execute_script( 'jscoverage_storeButton_click();' ) time.sleep( 1 ) browser.execute_script( 'jscoverage_recalculateSummaryTab();' ) summaryTable = browser.execute_script( 'return document.getElementById("summaryTable").innerHTML;' ) # parse the summary table data = summaryTable.replace( '\n', '' ).split( '</tr>' ) secondLine = data[1] totalNumberOfFiles = secondLine.split( '<span>' )[1].split( '</span>' )[0] totalLines = secondLine.split( '"numeric">' )[1].split( '</td>' )[0] totalTestedLines = secondLine.split( '"numeric">' )[2].split( '</td>' )[0] totalCoverage = secondLine.split( '"pct">' )[1].split( '%' )[0] covFiles = [] for i in range( 2, len( data ) - 1 ): line = data[i] fileName = line.split( '"#">' )[1].split( '</a>' )[0] lines = int( line.split( '"numeric">' )[1].split( '</td>' )[0] ) testedLines = int( line.split( '"numeric">' )[2].split( '</td>' )[0] ) untestedLines = lines - testedLines coveragePercent = line.split( '"pct">' )[1].split( '%' )[0] covFiles.append( [fileName, lines, testedLines, untestedLines, coveragePercent] ) # create XML from socket import getfqdn # WRITE XML from xml.dom import minidom # GET DATE #from cElementTree.SimpleXMLWriter import XMLWriter import string xml = minidom.Document() system_info = os.uname() siteElement = xml.createElement( 'Site' ) systeminfo = os.uname() siteElement.setAttribute( 'BuildName', system_info[0] + '-' + system_info[2] ) hostname = getfqdn() buildtype = 'Experimental' now = datetime.now() buildtime = str( now.year ) + str( now.month ) + str( now.day ) + "-" + str( now.minute ) + str( now.second ) #buildstamp = '20120603-0100-Nightly'# + '-' + buildtype buildstamp = buildtime + '-' + buildtype siteElement.setAttribute( 'BuildStamp', buildstamp ) siteElement.setAttribute( 'Name', hostname ) siteElement.setAttribute( 'Hostname', hostname ) xml.appendChild( siteElement ) buildElement = xml.createElement( 'Coverage' ) siteElement.appendChild( buildElement ) fillxml( xml, buildElement, 'StartDateTime', time.strftime( "%b %d %H:%M %Z", time.gmtime() ) ) fillxml( xml, buildElement, 'EndDateTime', time.strftime( "%b %d %H:%M %Z", time.gmtime() ) ) for f in covFiles: fileName = f[0] lines = f[1] testedLines = f[2] untestedLines = f[3] coveragePercent = f[4] fileElement = xml.createElement( 'File' ) fileElement.setAttribute( 'Name', os.path.split( fileName )[1] ) fileElement.setAttribute( 'FullPath', fileName ) fileElement.setAttribute( 'Covered', 'true' ) buildElement.appendChild( fileElement ) fillxml( xml, fileElement, 'LOCTested', str( testedLines ) ) fillxml( xml, fileElement, 'LOCUntested', str( untestedLines ) ) fillxml( xml, fileElement, 'PercentCoverage', str( coveragePercent ) ) fillxml( xml, buildElement, 'LOCTested', str( totalTestedLines ) ) fillxml( xml, buildElement, 'LOCUntested', str( int( totalLines ) - int( totalTestedLines ) ) ) fillxml( xml, buildElement, 'LOC', str( int( totalLines ) ) ) fillxml( xml, buildElement, 'PercentCoverage', str( totalCoverage ) ) f2 = open( 'XTKCoverage.xml', 'w' ) f2.write( xml.toxml() ) f2.close() browser.quit() return [result_unit, result]
def _test_bed(self): """Set up the test bed. Connect number of golden devices required by each case. """ browser = self._browser test_bed = browser.find_element_by_id('test-bed') time.sleep(3) history = HistoryHelper() selected_hw_set = test_bed.find_elements_by_class_name('selected-hw') selected_hw_num = len(selected_hw_set) while selected_hw_num: remove_button = selected_hw_set[selected_hw_num - 1].find_element_by_class_name( 'removeSelectedDevice') remove_button.click() selected_hw_num = selected_hw_num - 1 devices = filter(lambda port: not history.is_bad_golden_device(port), settings.GOLDEN_DEVICES) logger.info('Available golden devices: %s', json.dumps(devices, indent=2)) if len(devices) < self.golden_devices_required: raise Exception('Golden devices is not enough') golden_devices_required = self.golden_devices_required while golden_devices_required: golden_device = browser.find_element_by_id(settings.GOLDEN_DEVICE_TYPE) # drag action_chains = ActionChains(browser) action_chains.click_and_hold(golden_device) action_chains.move_to_element(test_bed).perform() time.sleep(1) # drop drop_hw = browser.find_element_by_class_name('drop-hw') action_chains = ActionChains(browser) action_chains.move_to_element(drop_hw) action_chains.release(drop_hw).perform() time.sleep(0.5) golden_devices_required = golden_devices_required - 1 selected_hw_set = test_bed.find_elements_by_class_name('selected-hw') for selected_hw in selected_hw_set: form_inputs = selected_hw.find_elements_by_tag_name('input') form_port = form_inputs[0] form_port.clear() device = devices.pop() form_port.send_keys(device) while True: try: self._connect_devices() elem = browser.find_element_by_id('nextBtn') if not self.wait_until(lambda: 'disabled' not in elem.get_attribute('class'), times=60): for selected_hw in selected_hw_set: form_inputs = selected_hw.find_elements_by_tag_name('input') form_port = form_inputs[0] if form_port.is_enabled(): port = form_port.get_attribute('value').encode('utf8') history.mark_bad_golden_device(port) if devices: device = devices.pop() form_port.clear() form_port.send_keys(device) else: devices = None if devices is None: logger.warning('Golden devices not enough') raise SystemExit() else: logger.info('Try again with new golden devices') continue elem.click() except SystemExit: raise except: logger.exception('Unexpected error') else: break
def _test_bed(self): """Set up the test bed. Connect number of golden devices required by each case. """ browser = self._browser test_bed = browser.find_element_by_id('test-bed') time.sleep(3) selected_hw_set = test_bed.find_elements_by_class_name('selected-hw') selected_hw_num = len(selected_hw_set) while selected_hw_num: remove_button = selected_hw_set[selected_hw_num - 1].find_element_by_class_name( 'removeSelectedDevice') remove_button.click() selected_hw_num = selected_hw_num - 1 devices = filter(lambda port: not (self.history.is_bad_golden_device(port) or (not self.auto_dut and port == settings.DUT_DEVICE )), settings.GOLDEN_DEVICES) logger.info('Available golden devices: %s', json.dumps(devices, indent=2)) golden_devices_required = self.golden_devices_required if self.auto_dut: golden_devices_required = golden_devices_required + 1 if len(devices) < golden_devices_required: raise Exception('Golden devices is not enough') device_type_id = settings.GOLDEN_DEVICE_TYPE if device_type_id == 'OpenThread': device_type_id = 'ARM' while golden_devices_required: device = browser.find_element_by_id(device_type_id) # drag action_chains = ActionChains(browser) action_chains.click_and_hold(device) action_chains.move_to_element(test_bed).perform() time.sleep(1) # drop drop_hw = browser.find_element_by_class_name('drop-hw') action_chains = ActionChains(browser) action_chains.move_to_element(drop_hw) action_chains.release(drop_hw).perform() time.sleep(0.5) golden_devices_required = golden_devices_required - 1 selected_hw_set = test_bed.find_elements_by_class_name('selected-hw') for selected_hw in selected_hw_set: form_inputs = selected_hw.find_elements_by_tag_name('input') form_port = form_inputs[0] form_port.clear() device = devices.pop() form_port.send_keys(device) while True: try: self._connect_devices() button_next = browser.find_element_by_id('nextBtn') if not self.wait_until(lambda: 'disabled' not in button_next.get_attribute('class'), times=(30 + 3 * golden_devices_required)): bad_ones = [] for selected_hw in selected_hw_set: form_inputs = selected_hw.find_elements_by_tag_name('input') form_port = form_inputs[0] if form_port.is_enabled(): bad_ones.append(selected_hw) for selected_hw in bad_ones: port = form_port.get_attribute('value').encode('utf8') if not settings.APC_HOST: # port cannot recover without power off self.history.mark_bad_golden_device(port) # remove the bad one selected_hw.find_element_by_class_name('removeSelectedDevice').click() time.sleep(0.1) device = browser.find_element_by_id(device_type_id) # drag action_chains = ActionChains(browser) action_chains.click_and_hold(device) action_chains.move_to_element(test_bed).perform() time.sleep(1) # drop drop_hw = browser.find_element_by_class_name('drop-hw') action_chains = ActionChains(browser) action_chains.move_to_element(drop_hw) action_chains.release(drop_hw).perform() time.sleep(0.5) selected_hw = browser.find_element_by_class_name('selected-hw') form_inputs = selected_hw.find_elements_by_tag_name('input') form_port = form_inputs[0] if devices: device = devices.pop() form_port.clear() form_port.send_keys(device) else: devices = None if devices is None: logger.warning('Golden devices not enough') raise SystemExit() else: logger.info('Try again with new golden devices') continue if self.auto_dut: checkbox_auto_dut = browser.find_element_by_id('EnableAutoDutSelection') if not checkbox_auto_dut.is_selected(): checkbox_auto_dut.click() radio_auto_dut = browser.find_element_by_class_name('AutoDUT_RadBtns') if not radio_auto_dut.is_selected(): radio_auto_dut.click() button_next.click() except SystemExit: raise except: logger.exception('Unexpected error') else: break
class Login(): def __init__(self): self.email='*****@*****.**' self.password='******' self.browser = webdriver.Chrome() self.browser.maximize_window() self.wait=WebDriverWait(self.browser,10) self.browser.get('https://auth.geetest.com/login/') self.action=ActionChains(self.browser) def user(self): email=self.browser.find_element(By.XPATH,'//*[@id="base"]/div[2]/div/div/div[3]/div/form/div[1]/div/div[1]/input') password=self.browser.find_element(By.XPATH,'//*[@id="base"]/div[2]/div/div/div[3]/div/form/div[2]/div/div[1]/input') self.action.click(email).perform() time.sleep(1) email.send_keys(self.email) time.sleep(1) self.action.click(password).perform() time.sleep(1) password.send_keys(self.password) def position(self): image=self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img'))) location=image.location location['x']=location['x'] location['y']=location['y'] size=image.size size['height']=size['height'] size['width']=size['width'] rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) return rangle def get_position1(self): #获取图片位置 button1=self.browser.find_element(By.CLASS_NAME,'geetest_radar_tip') self.action.click(button1).perform() #self.browser.switch_to.frame(self.browser.find_element_by_tag_name("iframe")) #image1=self.browser.find_element(By.XPATH,'/html/body/div[3]/div[2]/div[1]/div/div[1]/div[1]/div/a/div[1]/canvas') rangle=self.position() return rangle def get_position2(self): button2=self.browser.find_element(By.CLASS_NAME,'geetest_slider_button') button2.click() rangle=self.position() return rangle def image(self,rangle): screenshot=self.browser.get_screenshot_as_png() screenshot=Image.open(BytesIO(screenshot)) captche=screenshot.crop(rangle) return captche def get_image1(self): rangle=self.get_position1() time.sleep(2) captche=self.image(rangle) width=captche.size[0] height=captche.size[1] #captche = captche.resize((int(width*0.8), int(height*0.8)),Image.ANTIALIAS) captche.save('a.png') return captche def get_image2(self): rangle=self.get_position2() time.sleep(3) captche=self.image(rangle) width=captche.size[0] height=captche.size[1] #captche = captche.resize((int(width*0.8), int(height*0.8)),Image.ANTIALIAS) captche.save('b.png') return captche def is_pixel_equal(self, image1, image2, x, y): #判断两个像素是否相同 pixel1=image1.load()[x,y] pixel2=image2.load()[x,y] a=pixel1[0]-pixel2[0] b=pixel1[1]-pixel2[2] c=pixel1[2]-pixel2[2] threshold=60 if abs(a)<threshold and abs(b)<threshold and abs(c)<threshold: return True else: return False def get_gap(self, image1, image2): #获得缺口 left=60 #滑片宽度 for i in range(left, image1.size[0]): for j in range(image1.size[1]): if not self.is_pixel_equal(image1, image2, i, j): left = i return left return left def get_track(self,distance): #获得滑块的运动轨迹 track=[] current=0 v=0 t=0.2 m=distance*0.35 n=distance*0.7 while current<distance: if current<n: a=4 else: a=-6 v0=v v=v0+a*t move=v0*t+0.5*a*t*t current+=move track.append(round(move)) return track def move_to_grap(self): image1=self.get_image1() image2=self.get_image2() success=self.browser.find_element(By.CLASS_NAME,'geetest_success_radar_tip_content') slider=self.browser.find_element(By.CLASS_NAME,'geetest_slider_button') button=self.browser.find_element(By.CLASS_NAME,'ivu-btn') # +20多向前移动20的距离 distance=(self.get_gap(image1,image2)-6)+20 print(distance) track=self.get_track(distance) print(track) back_tracks=[-3,-3,-2,-2,-2,-2,-2,-1,-1,-1,-1] #待会回移的轨迹段 # while success.text!='验证成功': # for i in range(0,2): self.action.click_and_hold(slider) for x in track: self.action.move_by_offset(xoffset=x,yoffset=0) time.sleep(0.5) for y in back_tracks: self.action.move_by_offset(xoffset=y,yoffset=0) self.action.move_by_offset(xoffset=-3,yoffset=0) #小范围震荡 self.action.move_by_offset(xoffset=3,yoffset=0) time.sleep(0.5) self.action.release(slider) self.action.perform() time.sleep(2) # print(success.text) # if success.text=='验证成功': self.action.click(button).perform()
def resize_editor(self, editor): '''ensure that the editor is not covering the library (or else we cannot drag things from it!)''' browser = self.browser page_width = browser.get_window_size()['width'] lib_tab = self('library_tab').find_element_by_xpath('..') lib_width = lib_tab.size['width'] lib_position = lib_tab.location['x'] dialog_title = editor('dialog_title').find_element_by_xpath('../..') dialog_width = dialog_title.size['width'] dialog_position = dialog_title.location['x'] # how much overlap do we have? overlap = lib_position - (dialog_position + dialog_width) if overlap < 0: # we are overlapping # check to see if we have enough room to move out of the way if page_width < dialog_width + lib_width: # not enough, need to rezize the editor # look for the resize handle sibblings = dialog_title.find_elements_by_xpath('../../div') handle = None for sib in sibblings: if "ui-resizable-se" in sib.get_attribute('class'): handle = sib # do the resizing chain = ActionChains(browser) chain.click_and_hold(handle) # we can resize editor down to 425px, any less and we cover drop targets chain.move_by_offset(450 - dialog_width, 0).perform() # must click because release is not working. why? I do not know. chain.click().perform() chain.release(None).perform() # recalculate the overlap dialog_title = editor('dialog_title').find_element_by_xpath('../..') dialog_width = dialog_title.size['width'] dialog_position = dialog_title.location['x'] overlap = lib_position - (dialog_position + dialog_width) # We are good, move out! chain = ActionChains(browser) chain.click_and_hold(editor('dialog_title').element) chain.move_by_offset(overlap, 0).perform() # must click because release is not working. why? I do not know. chain.click().perform() chain.release(None).perform() # recalculate the overlap dialog_title = editor('dialog_title').find_element_by_xpath('../..') dialog_width = dialog_title.size['width'] dialog_position = dialog_title.location['x'] overlap = lib_position - (dialog_position + dialog_width) if overlap < 0: # we still have a problem. eq(True, False, "Could not move or rezise the editor dialog so it is not " "overlapping the library. The browser window is too small")