def navigate_to_specials(self): # Navigate to Specials tab and click it specials_id = self.driver.find_element_by_id(self.data_controller.config["site"]["locators"]["specials_id"]) navigate_to_specials = ActionChains(self.driver) navigate_to_specials.move_to_element_with_offset(specials_id, 5, 5) navigate_to_specials.click() navigate_to_specials.perform()
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 _drap_slider(self, slider_xpath, xoffset): """ 拉动滑块 :param slider_xpath: 滑块的xpath :param xoffset : 偏移量 :return : None """ total_length = round(self.zoom_rate * xoffset) - self.origin_xoffset slider = self.driver.find_element_by_xpath(slider_xpath) w = slider.size['width'] ActionChains(self.driver).click_and_hold(slider).perform() total_x = 0 # 累积偏移量 while True: xoffset = randint(self.min_xoffset, self.max_xoffset) # 随机偏移像素 yoffset = randint(-1, 1) total_x += xoffset if total_x > total_length: xoffset -= (total_x - total_length) total_x = total_length action = ActionChains(self.driver) action.move_to_element_with_offset(slider, xoffset + w / 2, yoffset).perform() # 随机暂停 sleep(uniform(self.min_sleep, self.max_sleep)) if total_x == total_length: break ActionChains(self.driver).release(slider).perform()
def submit_credentials(self): login_form_button = self.driver.find_elements_by_xpath( "*//div/button[@type='submit']")[0] login_action = ActionChains(self.driver) login_action.move_to_element_with_offset(login_form_button, 5, 5) login_action.click() login_action.perform()
def test_action_chains_鼠标(): driver = webdriver.Chrome() driver.implicitly_wait(10) driver.maximize_window() driver.get('http://sahitest.com/demo/mouseover.htm') write = driver.find_element_by_xpath( '//input[@value="Write on hover"]' ) # 鼠标移动到此元素,在下面的input框中会显示“Mouse moved” blank = driver.find_element_by_xpath( '//input[@value="Blank on hover"]') # 鼠标移动到此元素,会清空下面input框中的内容 result = driver.find_element_by_name('t1') action = ActionChains(driver) action.move_to_element(write).perform() # 移动到write元素,显示“Mouse moved” print(result.get_attribute('value')) # action.move_to_element(blank).perform() action.move_by_offset( 10, 50).perform() # 移动到距离当前位置(10,50)的点,与上句效果相同,移动到blank上,清空 print(result.get_attribute('value')) action.move_to_element_with_offset( blank, 10, -40).perform() # 移动到距离blank元素(10,-40)的点,可移动到write上 print(result.get_attribute('value')) time.sleep(2) driver.quit()
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 __show_all_comments(self, driver): show_more_comments_button = None while True: try: if show_more_comments_button is None: show_more_comments_button = self.__find_show_more_comments_button( driver) if show_more_comments_button is None: break if show_more_comments_button.is_enabled() is False: break actions = ActionChains(driver) actions.move_to_element_with_offset(show_more_comments_button, xoffset=0, yoffset=0) actions.perform() span = show_more_comments_button.find_element_by_tag_name( 'span') span.click() except Exception as e: print("Exception: ", e) break
def move_to_element_cordinate(self,locatorType,locator): act = ActionChains(self.driver) element=self.getElement(locatorType,locator) loc = element.location x_offset = loc['x'] y_offset = loc['y'] act.move_to_element_with_offset(element,x_offset,y_offset).perform()
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 click_img(self, answer, height, identify_img_xpath1=None, identify_button_xpath=None): """ 根据打码返回的坐标进行点击操作 仅适用与点击型验证码 :param answer: 打码返回结果 :param height: 答案高度 :param identify_img_xpath1: 题目xpath :param identify_button_xpath: 验证按钮 :return: """ actions = ActionChains(self.driver) img = self.driver.find_element_by_xpath(identify_img_xpath1) points = answer.split('|') for point in points: x, y = eval(point) actions.move_to_element_with_offset( img, x, y - int((height / self.device_pixel_ratio))) actions.click() actions.perform() time.sleep(2) if not identify_button_xpath: return self.driver.find_element_by_xpath(identify_button_xpath).click()
def graph_some_value(context, graph_title): #find the right graph graph_label = context.browser.find_element_by_xpath('//h3[contains(text(), "%s")]' % graph_title) graph_panel = graph_label.find_element_by_xpath('./../..') graph_container = graph_panel.find_element_by_id('container') #search the page source for the value timeout = time() + int(120) while time() < timeout: #click on the canvas to show the value from selenium.webdriver.common import action_chains, keys action_chain = ActionChains(context.browser) action_chain.move_to_element_with_offset(graph_panel, 600, 150) action_chain.click() action_chain.perform() src = context.browser.page_source if graph_title == 'Load on all monitored machines': # graph in dashboard machine = context.mist_config['monitored-machine-random'] text_found = re.search(machine + r" : [0-999]", src) else: text_found = re.search(graph_title.capitalize() + r" : [0-999]", src) if text_found: return else: sleep(2) assert False, 'Graph does not have any values'
class TextEditorHelper: def __init__(self, driver): self.driver = driver self.environmentSelectorDropdownItem = self.driver.find_element_by_xpath( ".//span[contains(text(),'Python 2.7')]") self.actions = ActionChains(self.driver) def scrollIntoView(self): self.driver.execute_script( "arguments[0].scrollIntoView();", self.driver.find_element_by_id("codeSection")) def moveToTextEditor(self): self.actions.move_to_element_with_offset( self.environmentSelectorDropdownItem, 0, 200) self.actions.click() self.actions.perform() def deleteCode(self): self.actions.key_down(Keys.LEFT_CONTROL).send_keys('a').key_up( Keys.LEFT_CONTROL).perform() self.actions.send_keys(Keys.DELETE).perform() def addCode(self, code): self.actions.send_keys(code) self.actions.perform()
def login(self): '''登录12306''' time.sleep(1) #点击账号登录 self.wait.until( EC.visibility_of_element_located((By.LINK_TEXT, '账号登录'))).click() time.sleep(1) self.browser.find_element_by_id('J-userName').send_keys(self.userName) time.sleep(1) self.browser.find_element_by_id('J-password').send_keys(self.pwd) #获取验证码图片和验证码对象 login_img, login_img_element = self.get_code_img() #识别验证码 result = yundama('login_img.png', 6701) #str = ','.join(result) #print('识别结果:第{}张图片'.format(str)) positions = [ (40, 75), (118, 71), (170, 64), (265, 65), (22, 139), (129, 146), (184, 150), (276, 140), ] for num in result: position = positions[int(num) - 1] action = ActionChains(self.browser) time.sleep(random.uniform(0.5, 1)) action.move_to_element_with_offset(login_img_element, position[0], position[1]).click().perform() time.sleep(1) self.browser.find_element_by_id('J-login').click()
def _test_apply_modal( self, brightness_slider: WebElement, contrast_slider: WebElement, driver: WebDriver, image_view_port_elem: WebElement, ) -> None: move_sliders = ActionChains(driver) brightness_slider_size = brightness_slider.size contrast_slider_size = contrast_slider.size move_sliders.move_to_element_with_offset( to_element=brightness_slider, xoffset=brightness_slider_size['width'] - 1, yoffset=brightness_slider_size['height'] / 2, ) move_sliders.click() move_sliders.move_to_element_with_offset( to_element=contrast_slider, xoffset=contrast_slider_size['width'] - 1, yoffset=contrast_slider_size['height'] / 2, ) move_sliders.click() move_sliders.perform() apply_button = driver.find_element_by_id( 'id_apply_image_editor_button', ) apply_button.click() filter_style = image_view_port_elem.value_of_css_property('filter') self.assertEqual('invert(0) contrast(2) brightness(2)', filter_style)
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 like_post(self): no_likes_title = self.driver.find_elements_by_xpath(NO_LIKES_TITLE) # Check if post have some likes if len(no_likes_title) < 1: likes_counter = self.driver.find_element_by_xpath(LIKES_COUNTER) likes_counter.click() print('Post likes amount - %s' % likes_counter.text) liked_counter_value = int(likes_counter.text) + 1 action = ActionChains(self.driver) action.move_to_element_with_offset(likes_counter, 0, -20).click().perform() print('User taps on like button') print('Checking if likes counter is updated...') print('Post new likes amount - %s' % likes_counter.text) self.assertIn(str(liked_counter_value), likes_counter.text) else: no_likes_text = self.driver.find_element_by_xpath(NO_LIKES_TITLE) no_likes_view = self.driver.find_element_by_xpath(NO_LIKES_VIEW) print('Nobody likes this post') print(no_likes_text.text) no_likes_view.click() print('User scrolls to likes block') action = ActionChains(self.driver) print('User taps on like button') action.move_to_element_with_offset(no_likes_text, -10, 0).click().perform() print('Checking if likes counter is updated...') self.driver.implicitly_wait(5) likes_counter = self.driver.find_element_by_xpath(LIKES_COUNTER) print('Post new likes amount - %s' % likes_counter.text)
def test_get_themes_list_and_open_random(self): driver = self.driver # Get themes list as WebElement objects theme_elem = driver.find_elements_by_css_selector( 'span.project-navigation__sign') themes = [] # Filling themes for i in range(0, len(theme_elem)): if theme_elem[i].text != '': themes.append(theme_elem[i]) # Select random theme random_element = random.sample(themes, 1)[0] random_element_text = random_element.text # Actions(MouseClick) action = ActionChains(driver) action.move_to_element_with_offset(random_element, 5, 5) action.click() action.perform() theme_title = driver.find_element_by_class_name("schema-header__title") self.assertEqual(random_element_text, theme_title.text)
def test_horizontal_slider(driver): # Кликаем на слайдер и проверяем значения focus = driver.find_element_by_css_selector('input[type=range]') focus.click() span = driver.find_element_by_css_selector('#range:nth-child(2)') assert span.text == "2.5" # Перетскиваем слайдер мышкой time.sleep(1) action = ActionChains(driver) action.move_to_element_with_offset(focus, 100, 0).click().perform() assert span.text == "4" # Перетаскиваем слайддер клавишами time.sleep(1) focus.send_keys(Keys.ARROW_LEFT) assert span.text == "3.5" time.sleep(1) focus.send_keys(Keys.ARROW_DOWN) assert span.text == "3" time.sleep(1) focus.send_keys(Keys.ARROW_RIGHT) assert span.text == "3.5" time.sleep(1) focus.send_keys(Keys.ARROW_UP) assert span.text == "4"
def move_to_element_with_offset_and_click(self, loc=None, ele=None, strict=True, xoffset=0, yoffset=0, action='click'): if not (loc or ele): LOG_ERROR('loc: {}, ele: {}, 请至少输入一个有效参数!'.format(loc, ele)) else: if not ele: ele = self.find_element(loc, strict=strict) if ele: action_select = ['click', 'double_click', 'context_click'] if action not in action_select: LOG_DEBUG('action: {}参数错误, 可选参数为: {}'.format(action, action_select)) try: self.driver.execute_script("arguments[0].scrollIntoView();", ele) LOG_DEBUG('移动到坐标 {}'.format(ele.location)) actions = ActionChains(self.driver) LOG_DEBUG('移动当前坐标的相对坐标 x: {}, y: {}, 点击坐标'.format(xoffset, yoffset)) actions.move_to_element_with_offset(ele, xoffset, yoffset) if action == 'click': actions.click() elif action == 'double_click': actions.double_click() elif action == 'context_click': actions.context_click() else: pass actions.perform() except Exception as e: LOG_DEBUG('移动坐标失败: {}'.format(e))
def loginOk(self, login): if self.retry > 10: raise RetryToMuch() try: self.wait.until( EC.text_to_be_present_in_element( (By.CSS_SELECTOR, "#normal_passenger_id li label"), TICKET.get('name'))) except TimeoutException: print("验证码错误,或者超时") #刷新验证码 重新登录 pic_loaded = self.wait.until( # 账号登录 element_attr_to_be_present((By.ID, "J-loginImg"), 'src', r'base64,')) actions = ActionChains(self.drive) actions.move_to_element_with_offset(pic_loaded, 288, 13) actions.click() actions.perform() # 点击更新按钮 try: self.wait.until( # 等待图片更新 element_attr_has_changed((By.ID, "J-loginImg"), 'src')) except TimeoutException: print("图片并未更新") login.clickLoginBtn() self.loginOk(login)
def move(game, board): original_game = game original_board = board # predict move board.set_fen(display_board(game)[1].fen()) if not chess.Color(chess.WHITE) or board.is_game_over(): return game, board result = engine.play(board, chess.engine.Limit(time=1)) board.push(result.move) print(result.move) print("from ", result.move.from_square) print("to ", result.move.to_square) from_square_x, from_square_y = translate(result.move.from_square) to_square_x, to_square_y = translate(result.move.to_square) print("translated:", "square-" + str(from_square_x) + str(from_square_y)) WebDriverWait(game, 20).until(expected_conditions.presence_of_element_located( (By.CLASS_NAME, "square-" + str(from_square_x) + str(from_square_y)))) game.find_elements_by_class_name("square-" + str(from_square_x) + str(from_square_y))[0].click() time.sleep(1.5) action = ActionChains(game) clickable = game.find_elements_by_class_name("coordinates")[0] x, y = get_element_by_board_cords(game, to_square_x, to_square_y) action.move_to_element_with_offset(clickable, x, y) action.click() action.perform() time.sleep(1.5) if board.fen() != display_board(game)[1].fen(): move(original_game, original_board) return game, board
def put_element_on_grid(self, type_str): '''find 'type_str' in the Library, drag and drop it onto the grid''' browser = self.browser grid = browser.find_element_by_xpath('//div[@id="-dataflow"]') for retry in range(3): try: objtype = self.find_library_button(type_str) chain = ActionChains(browser) chain.click_and_hold(objtype) chain.move_to_element_with_offset(grid, 10, 10).perform() except StaleElementReferenceException: if retry < 2: logging.warning( 'put_element_on_grid %s:' ' StaleElementReferenceException', type_str) else: raise else: break self.check_highlighting(grid, True, "Grid") self.release(chain) # deal with the modal dialog name = NameInstanceDialog(self).create_and_dismiss() # make sure it is on the grid self.ensure_names_in_workspace( [name], "Dragging '" + type_str + "' to grid did not produce a new element on page") return name
def loginOk(self): if self.retry > 10: print("retry count has more than 10,exit!") return try: self.wait.until( # 账号登录 login_url_has_ok(LOGIN_OK)) except TimeoutException: print("验证码错误,或者超时") #刷新验证码 重新登录 pic_loaded = self.wait.until( # 账号登录 element_attr_to_be_present((By.ID, "J-loginImg"), 'src', r'base64,')) actions = ActionChains(self.drive) actions.move_to_element_with_offset(pic_loaded, 288, 13) actions.click() actions.perform() # 点击更新按钮 try: self.wait.until( # 等待图片更新 element_attr_has_changed((By.ID, "J-loginImg"), 'src')) except TimeoutException: print("图片并未更新") self.clickLoginBtn() self.loginOk()
def put_element_on_grid(self, type_str): '''find 'type_str' in the Library, drag and drop it onto the grid''' browser = self.browser grid = browser.find_element_by_xpath('//div[@id="-dataflow"]') for retry in range(3): try: objtype = self.find_library_button(type_str) chain = ActionChains(browser) chain.click_and_hold(objtype) chain.move_to_element_with_offset(grid, 10, 10).perform() except StaleElementReferenceException: if retry < 2: logging.warning('put_element_on_grid %s:' ' StaleElementReferenceException', type_str) else: raise else: break self.check_highlighting(grid, True, "Grid") self.release(chain) # deal with the modal dialog name = NameInstanceDialog(self).create_and_dismiss() # make sure it is on the grid self.ensure_names_in_workspace([name], "Dragging '" + type_str + "' to grid did not produce a new element on page") return name
def click_on_the_element_end(self): print('click_on_element_at_the_end by locator') elm = self.find_element() size = self.get_size() action = ActionChains(self.driver) action.move_to_element_with_offset(elm, size['width'] - 1, size['height'] - 1) action.click() action.perform()
def connections_page(self): """ Return :class:`ConnectionsPage` for this component. """ chain = ActionChains(self.browser) chain.move_to_element_with_offset(self.root, 15, 15).context_click(None).perform() self('connections_button').click() frame_id = 'ConnectionsFrame-%s' % self.pathname.replace('.', '-') return ConnectionsPage(self.browser, self.port, (By.ID, frame_id))
def show_connected_variables(self): """ Show only the connected variables. """ chain = ActionChains(self.browser) chain.move_to_element_with_offset(self.connections_pane, 5, 5) chain.context_click(None) chain.perform() time.sleep(0.5) self('show_connected_button').click()
def click100_by_tag(self, tag): # 保证可以点击到的方法 time.sleep(0.01) action_chains = ActionChains(self.driver) action_chains.move_to_element_with_offset(tag, 10, 10) action_chains.click() action_chains.perform() print("完成100TAG按键操作")
def flip(self): """ Flip the workflow from horizontal to vertical or vice versa. """ chain = ActionChains(self.browser) chain.move_to_element_with_offset(self.flow, 5, 5) chain.context_click(None) chain.perform() time.sleep(0.5) self('flip_button').click()
def move_mouse_to_volume_bar(self): """ Moves the mouse over to the volume bar. """ actions = ActionChains(self.SABL.ret_driver()) actions.move_to_element_with_offset(self.SABL.mute_button(), 60, 20) actions.pause(5) actions.perform()
def click100(self, tagId): time.sleep(1) action_chains = ActionChains(self.driver) action_chains.move_to_element_with_offset( self.driver.find_element_by_id(tagId), 10, 10) action_chains.click() action_chains.perform() print("完成按键操作", tagId)
def clear(self): """ Clear the workflow. """ chain = ActionChains(self.browser) chain.move_to_element_with_offset(self.flow, 5, 5) chain.context_click(None) chain.perform() time.sleep(0.5) self('clear_button').click()
def close_slider(self, by_area=0): if by_area: btn_close = self.driver.find_element_by_class_name(self.CLOSE_AREA) actions = ActionChains(self.driver) actions.move_to_element_with_offset(btn_close, 0, 0).click().perform() else: btn_close = self.driver.find_element_by_class_name(self.CLOSE_CLASS) btn_close.click()
def select_item(self, language): # Wait for menu items to appear, then click item link_text = self.driver.find_element_by_link_text( self.data_controller.config["site"]["locators"]["link_text"][language]) select_item = ActionChains(self.driver) select_item.move_to_element_with_offset(link_text, 5, 5) select_item.click() select_item.perform()
def evaluate(self): """ Evaluate this component. (only available for ImplicitComponent) """ rect = self.root.find_element_by_css_selector('rect') chain = ActionChains(self.browser) chain.move_to_element_with_offset(rect, 15, 15) chain.context_click(None) chain.perform() time.sleep(0.5) self('evaluate_button').click()
def clicketi_click_list_row(context, item): """ This is a special clicketi click for list items that might not be clickable in the middle. """ action_chain = ActionChains(context.browser) action_chain.move_to_element_with_offset(item, item.size['width'] / 4, item.size['height'] / 2) action_chain.click() action_chain.perform()
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 run(self): """ Run this component. """ rect = self.root.find_element_by_css_selector('rect') chain = ActionChains(self.browser) chain.move_to_element_with_offset(rect, 15, 15) chain.context_click(None) chain.perform() time.sleep(0.5) self('run_button').click()
def _context_click(self, name): """ Display context menu. """ chain = ActionChains(self.browser) # Default is centered which causes problems in some contexts. # Offset is apparently limited, (20, 20) had problems. chain.move_to_element_with_offset(self.root, 15, 15) chain.context_click(None) chain.perform() time.sleep(0.5) self(name).click()
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 unlike_post(self): likes_counter = self.driver.find_element_by_xpath(LIKES_COUNTER) likes_counter.click() print('Post likes amount - %s' % likes_counter.text) liked_counter_value = int(likes_counter.text) - 1 action = ActionChains(self.driver) action.move_to_element_with_offset(likes_counter, 0, -20).click().perform() print('User taps on unlike button') print('Checking if likes counter is updated...') print('Post new likes amount - %s' % likes_counter.text) self.assertIn(str(liked_counter_value), likes_counter.text)
def _context_click(self, name): """ Display context menu. """ chain = ActionChains(self.browser) # Just using center of self.root had an isolated 'overlap' failure. chain.move_to_element_with_offset(self('data').element, 2, 2) chain.context_click(None) chain.perform() time.sleep(0.5) # Wait for menu to display. text = self(name).text self(name).click() time.sleep(0.5) # Wait to pop-down. return text
def drag_element_to(self, element, drag_to, center): '''Drag one element over to another element''' chain = ActionChains(self.browser) chain.move_to_element(element) chain.click_and_hold(element) if center: # move to center of element chain.move_to_element(drag_to) else: # move to offset from top left of element chain.move_to_element_with_offset(drag_to, 2, 2) chain.perform() return chain
def simulate_verify(self, codes): cap = self.browser.find_element_by_id('captcha-body') if cap is None: logging.error("captcha body not found") return actions = ActionChains(self.browser) actions.move_to_element(cap).perform() for x, y in codes: print(x, y) actions = ActionChains(self.browser) actions.move_to_element_with_offset(cap, x, y).click().perform() time.sleep(self.short_sleep) time.sleep(self.mid_sleep) btn = self.browser.find_element_by_id('captcha-submitCode') btn.click()
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 autoclick_sparse_click(dom_element): global browser random.seed(None) h = dom_element.size['height'] w = dom_element.size['width'] xoff = random.randint(w/2 - w/3, w/2 + w/3) yoff = random.randint(h/2 - h/3, h/2 + h/3) try: action = ActionChains(browser) action.move_to_element_with_offset(dom_element, xoff, yoff) action.click() action.perform() except NoSuchElementException as err: return False return True
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 _add_dataset(self, browser, organization): """ Add a simple dataset. Return dataset address. """ browser.get("https://localhost/en/dataset/new") browser.implicitly_wait(8) # Wait for javascript magic to alter fields try: field = browser.find_element_by_xpath("//input[@id='langtitle__0__value_id']") field.send_keys('Selenium Dataset') field = browser.find_element_by_xpath("//input[@name='agent__0__name']") field.send_keys('Selenium') field = browser.find_element_by_xpath("//input[@name='agent__0__organisation']") field.send_keys('CSC Oy') # Keywords -- the actual autocomplete field lacks the id attribute, so find it through an ancestor's sibling field = browser.find_element_by_xpath( "//input[@id='field-tags']/../div[@class='select2-container select2-container-multi']//input") field.send_keys('Selenium') field.send_keys(Keys.RETURN) field = browser.find_element_by_xpath("//input[@name='langdis']") field.click() field = browser.find_element_by_xpath("//input[@id='contact__0__name']") field.send_keys('Selenium contact') field = browser.find_element_by_xpath("//input[@id='contact__0__email']") field.send_keys('*****@*****.**') field = browser.find_element_by_xpath("//input[@id='contact__0__URL']") field.send_keys('https://localhost/') field = browser.find_element_by_xpath("//input[@id='contact__0__phone']") field.send_keys('+35891234567') field = browser.find_element_by_xpath("//input[@id='contact_owner']") field.click() field = browser.find_element_by_xpath("//input[@name='agent__3__name']") field.send_keys('Selenium') # field = browser.find_element_by_xpath("//select[@id='field-kata-pr']/option[@value='False']") # field.click() # field.send_keys('Published') field = browser.find_element_by_xpath( "//section/div/div/div/div[label[text()='Organisation']]/div/div/a") # CKAN Generated field ac = ActionChains(browser) ac.move_to_element_with_offset(field, 0.1, 0.1).click().perform() browser.implicitly_wait(2) for o in list(organization) + [Keys.RETURN]: ac.send_keys(o).perform() browser.implicitly_wait(2) browser.find_element_by_name("kata-accept-terms").click() browser.find_element_by_xpath("//*[contains(text(), 'Save and publish')]").click() except NoSuchElementException: browser.get_screenshot_as_file('_add_dataset.png') assert 0, "Error processing the create dataset page" try: WebDriverWait(browser, 30).until(expected_conditions.presence_of_element_located((By.XPATH, "//article/div/a[.='Hide/show']"))) except TimeoutException: browser.get_screenshot_as_file('_add_dataset.png') browser.quit() assert 0, "Dataset creation didn't finish" if not "Selenium Dataset" in browser.title: browser.get_screenshot_as_file('_add_dataset.png') browser.quit() assert 0, "Dataset creation failed somehow" return ''.join(browser.current_url)
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 selectMenuItemFromUIElement(driver, parentAXPath, menuItemTitles, lastItemOperation): if len(menuItemTitles) < 1: return "" # When selecting menu items from a menu, we don't need to wait very long for elements to appear. driver.implicitly_wait(0.5) parentUIElement = findElementByXPath(driver, parentAXPath) elementAXPath = "" # Iterate through the menuItems and subMenuItems. lastIndex = len(menuItemTitles) for titleIndex in range(0, lastIndex): # The parent may be an AXMenu, or it may be something like AXFocusedElement, # so don't add AXMenu until we get into sub-menus. if titleIndex > 0: parentAXPath = parentAXPath + "/AXMenu" elementAXPath = parentAXPath + "/AXMenuItem[@AXTitle='" + menuItemTitles[titleIndex] + "'" # Append the lastItemOperation to the last element if titleIndex == lastIndex - 1 and type(lastItemOperation) is str and len(lastItemOperation) > 0: elementAXPath = elementAXPath + lastItemOperation elementAXPath = elementAXPath + "]" element = findElementByXPath(driver, elementAXPath) if element == None: elementAXPath = "" break eSize = element.size eLocation = element.location actions = ActionChains(driver) if element.location['x'] <= parentUIElement.location['x']: # The (sub)menu item is either to the left or under its parent menu item. # Move the mouse to the left of its parent menu item first. # This avoids passing over other menu items, which can change the highlighted menu item. # (Don't do this on the first menu item, because our caller already did it.) if titleIndex > 0: actions.move_to_element_with_offset(parentUIElement, 1, 10) actions.move_to_element_with_offset(element, 20, 10) else: # The (sub)menu item is to the right of its parent menu item. # Move the mouse to the right of its parent menu item first. # This avoids passing over other menu items, which can change the highlighted menu item. # (Don't do this on the first menu item, because our caller already did it.) if titleIndex > 0: actions.move_to_element_with_offset(parentUIElement, parentUIElement.size['width'] - 1, 10) actions.move_to_element_with_offset(element, 20, 10) actions.click().perform() parentAXPath = elementAXPath parentUIElement = element driver.implicitly_wait(defaultImplicitTimeout_sec) # If we did not select from the visible menu, press esc to cancel menu selection. if len(elementAXPath) == 0: #print "len(elementAXPath) == 0. Pressing escape." ActionChains(driver).send_keys(Keys.ESCAPE).perform() return elementAXPath
def center_dbclick(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.double_click().perform()
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]