我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用selenium.webdriver.common.action_chains.ActionChains()。
def random_youtube(): iterations = randint(1,8) count = 0 while(1): item = words[randint(0,len(words))] driver.get("https://www.youtube.com/results?search_query="+item) element = driver.find_element_by_class_name('yt-uix-tile-link') element.click() actions = ActionChains(driver) actions.send_keys('K') actions.perform() time.sleep(randint(15,50)) print "currently on site: " + driver.current_url count = count +1 if count == iterations: break;
def login_user(browser, username, password): """Logins the user with the given username and password""" browser.get('https://twitter.com/login') #Enter username and password and logs the user in userContainer = browser.find_element_by_xpath('//input[contains(@class, "js-username-field email-input js-initial-focus")]') passwordContainer = browser.find_element_by_xpath('//input[@type = "password"]') action = ActionChains(browser).move_to_element(userContainer).click().send_keys(username) \ .send_keys(Keys.TAB).send_keys(password).perform() submitButton = browser.find_element_by_xpath('//button[@type = "submit"]') action = ActionChains(browser).move_to_element(submitButton).click().perform() sleep(2) #Check if user is logged-in (If there's two 'nav' elements) prof = browser.find_elements_by_xpath('//div[@class = "DashboardProfileCard-content"]') if len(prof) > 0: return True else: return False
def drag_and_drop_on(self, other): """ Drag and drop this element on to another element instance Note that browser support may vary :param other: element to drop on :Example: Drag an element onto another a = browser.div(id='draggable') b = browser.div(id='droppable') a.drag_and_drop_on(b) """ self._assert_is_element(other) value = self._element_call(lambda: ActionChains(self.driver) .drag_and_drop(self.el, other.wd).perform(), self.wait_for_present) self.browser.after_hooks.run() return value
def hover_on_element(element): """Hover over an element Arguments: element -- the Selenium WebDriver Element to hover on Returns: True of False """ if verbose: print 'Hovering on element...' try: actions = ActionChains(Browser) actions.move_to_element(element) actions.perform() return True except: return False
def hacker_typing(browser, spinter_selection, code): """We need to break Splinter abstraction and fall back to raw Selenium here. Note: There is a bug of entering parenthesis due to IPython capturing keyboard input. http://stackoverflow.com/questions/22168651/how-to-enter-left-parentheses-into-a-text-box """ elem = spinter_selection[0]._element driver = browser.driver # Activate IPython input mode ActionChains(driver).click(elem).send_keys(Keys.ENTER).perform() # Type in the code a = ActionChains(driver) a.send_keys(code) a.perform() time.sleep(1.0) # Execute the text we just typed a = ActionChains(driver) a.key_down(Keys.SHIFT).send_keys(Keys.ENTER).key_up(Keys.SHIFT) a.perform()
def drag_and_drop_test(self, x_offset=0, y_offset=0, element_class="gt_slider_knob"): """???? :x_offset: ????x???? :y_offset: ????y???? :element_class: ??????CSS?? :use for: ????????????? """ dragger = self.driver.find_element_by_class_name(element_class) action = ActionChains(self.driver) action.drag_and_drop_by_offset(dragger, x_offset, y_offset).perform() time.sleep(2.8)
def process(self,caption_text): time.sleep(1) caption_text #self.driver.get("https://www.facebook.com") actions = ActionChains(self.driver) time.sleep(2) actions.send_keys('p').perform() time.sleep(1) caption = ActionChains(self.driver) caption.send_keys(caption_text).perform() click_post = self.driver.find_element_by_xpath('//div[2]/div[3]/div/div[2]/div/button') click_post.click() print "Successfully posted " self.driver.close() #text = raw_input("Enter text to be posted - ")
def mouse_down(self, locator): """Simulates pressing the left mouse button on the element specified by `locator`. The element is pressed without releasing the mouse button. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. See also the more specific keywords `Mouse Down On Image` and `Mouse Down On Link`. """ self._info("Simulating Mouse Down on element '%s'" % locator) element = self._element_find(locator, True, False) if element is None: raise AssertionError("ERROR: Element %s not found." % (locator)) ActionChains(self._current_browser()).click_and_hold(element).perform()
def test_file_upload_tooltips(driver, project): driver.get('/') driver.refresh() driver.find_element_by_id('react-tabs-2').click() driver.find_element_by_partial_link_text('Upload new dataset').click() header_file = driver.find_element_by_css_selector('[name=headerFile]') hover = ActionChains(driver).move_to_element(header_file) hover.perform() time.sleep(0.8) assert driver.find_element_by_xpath( "//span[contains(.,'filename,label')]" ).is_displayed() tar_file = driver.find_element_by_css_selector('[name=tarFile]') hover = ActionChains(driver).move_to_element(tar_file) hover.perform() time.sleep(0.8) assert driver.find_element_by_xpath( "//span[contains(.,'Each file in tarball should be formatted as follows')]" ).is_displayed()
def Click_and_Hold_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: click_and_hold = ActionChains(selenium_driver).click_and_hold(Element) click_and_hold.perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully clicked and held the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not click and hold your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to right click on element; step data passed on by the user
def Context_Click_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: context_click = ActionChains(selenium_driver).context_click(Element) context_click.perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully right clicked the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not right click your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to double click on element; step data passed on by the user
def Double_Click_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: double_click = ActionChains(selenium_driver).double_click(Element) double_click.perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully double clicked the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not double click your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to move to middle of the element; step data passed on by the user
def Move_To_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: move = ActionChains(selenium_driver).move_to_element(Element).perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully moved to the middle of the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not move to your element your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to hover over element; step data passed on by the user
def Hover_Over_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: hov = ActionChains(selenium_driver).move_to_element(Element) hov.perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully hovered over the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not select/hover over your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def hover(self, locator, replacement=None): """Mouse over on element :param locator: element locator :param replacement: if locator contains dynamic part, i.e. '$value', it will be replaced by replacement variable :return: None """ if replacement is not None: locator = locator.replace('$value', replacement) try: element = self.fetch_element(locator) mouse_hover = ActionChains(self.context.driver).move_to_element(element) mouse_hover.perform() except Exception as e: self.context.logger.error("Unable to hover on locator '" + locator + "'. Error: %s" % e, exc_info=True) Assert.assert_fail("Unable to hover on locator '" + locator + "'")
def clk(driver, url): """locate and click url""" locator = (By.XPATH, '//span[contains(text(), "{0}")]/../../../../a'.format(url)) try: WebDriverWait(driver, 5, 0.5).until(EC.element_to_be_clickable(locator)) try: moved_to_element = driver.find_element_by_xpath('//span[contains(text(), "{0}")]'.format(url)) target_element = driver.find_element(*locator) ActionChains(driver).move_to_element(to_element=moved_to_element).click(target_element).perform() sleep(1) if 'm.baidu.com' in driver.current_url: target_element.click() return 1 except: return 0 except TimeoutException: return 0
def click_add_folder(self, folder_id): """Click the "Add" link in the old AM file explorer interface, i.e., to add a directory to a transfer. """ block = WebDriverWait(self.driver, 10) block.until(EC.presence_of_element_located( (By.ID, folder_id))) folder_elem = self.driver.find_element_by_id(folder_id) hover = ActionChains(self.driver).move_to_element(folder_elem) hover.perform() time.sleep(0.25) # seems to be necessary (! jQuery animations?) span_elem = self.driver.find_element_by_css_selector( 'div#{} span.{}'.format(folder_id, self.add_transfer_folder_class)) hover = ActionChains(self.driver).move_to_element(span_elem) hover.perform() span_elem.click()
def Transfer_Clicks(browser): try: browser.execute_script("window.scrollBy(0,document.body.scrollHeight)", "") # ???????Javascript?????????????? # browser.execute_script("window.scrollBy(0,5)", "") # ????200????????????? # ActionChains(browser).move_by_offset(0,-80).perform() # ??????80?????????? # ActionChains(browser).click().perform() # ?????? # ActionChains(browser).key_down(Keys.TAB).perform() # ??tab???? # ActionChains(browser).send_keys(Keys.ENTER).perform() # ????ENTER? except: pass return "Transfer successfully \n"
def hover(self, by, value, message = None): element = self.assertElementPresent(by, value, message = message) self.log("Hover mouse over {0}".format(self.describeElement(by, value))) hoverAction = ActionChains(self.driver).move_to_element(element) if not hoverAction: self.onFail(by, value, message, "Unable to move to") hoverAction.perform() return element
def drag_and_drop(self, x_offset=0, y_offset=0, element_class="gt_slider_knob"): """???? :x_offset: ????x???? :y_offset: ????y???? :element_class: ??????CSS?? """ dragger = self.driver.find_element_by_class_name(element_class) action = ActionChains(self.driver) action.drag_and_drop_by_offset(dragger, x_offset, y_offset).perform() # ?????????????????? time.sleep(8)
def move_to_element(self, element_class="gt_slider_knob"): """?????????? :element: ?????? """ time.sleep(3) element = self.driver.find_element_by_class_name(element_class) action = ActionChains(self.driver) action.move_to_element(element).perform() time.sleep(4.5)
def test_teacher_add_an_ext_assignment_by_drag_and_drop_146504(self): """ Steps: Click on the 'Add Assignment' menu Click and Drag 'Add External Assignment' to a chosen due date Expected result: User is taken to 'Add External Assignment' page, and due date is filled in as date dragged to """ self.ps.test_updates['name'] = 'tutor_external_teacher' \ + inspect.currentframe().f_code.co_name[ 4:] self.ps.test_updates['tags'] = ['tutor', 'external', 'teacher', '146504'] self.ps.test_updates['passed'] = False # Test verification self.teacher.assign.open_assignment_menu(self.teacher.driver) external_tab = self.teacher.find( By.LINK_TEXT, 'Add External Assignment' ) due_date = self.teacher.wait.until( expect.element_to_be_clickable( (By.XPATH, '//div[contains(@class,"Day--upcoming")]') ) ) actions = ActionChains(self.teacher.driver) actions.move_to_element(external_tab) actions.drag_and_drop(external_tab, due_date).perform() sleep(3) assert ('external/new' in self.teacher.current_url()), \ 'not at Add External Assignment page' self.ps.test_updates['passed'] = True # Case C146505 017 - Teacher | Info Icons
def test_teacher_add_an_event_by_drag_and_drop_162187(self): self.ps.test_updates['name'] = 'tutor_event_teacher' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['tutor', 'event', 'teacher', '162187'] self.ps.test_updates['passed'] = False # Test verification self.teacher.assign.open_assignment_menu(self.teacher.driver) event_tab = self.teacher.find( By.LINK_TEXT, 'Add Event' ) due_date = self.teacher.wait.until( expect.element_to_be_clickable( (By.XPATH, '//div[contains(@class,"Day--upcoming")]') ) ) actions = ActionChains(self.teacher.driver) actions.move_to_element(event_tab) actions.drag_and_drop(event_tab, due_date).perform() sleep(3) assert ('event/new' in self.teacher.current_url()), \ 'not at Add Event page' self.ps.test_updates['passed'] = True # Case C162188 017 Teacher| Get assignment link test info icons
def mouseClick(css:str): global driver actions = ActionChains(driver) el = waitElem(css) actions.move_to_element(el).click().perform()
def click(self, *modifiers): """ Clicks the element, optionally while pressing the given modifier keys. Note that support for holding a modifier key is currently experimental, and may not work at all. :param modifiers: modifier keys to press while clicking :Example: Click an element browser.element(name='new_user_button').click() :Example: Click an element with shift key pressed from selenium.webdriver.common.keys import Keys browser.element(name='new_user_button').click(Keys.SHIFT) :Example: Click an element with several modifier keys pressed from selenium.webdriver.common.keys import Keys browser.element(name='new_user_button').click(Keys.SHIFT, Keys.CONTROL) """ def method(): if modifiers: action = ActionChains(self.driver) for mod in modifiers: action.key_down(mod) action.click(self.el) for mod in modifiers: action.key_up(mod) action.perform() else: self.el.click() self._element_call(method, self.wait_for_enabled) self.browser.after_hooks.run()
def double_click(self): """ Double clicks the element. Note that browser support may vary. :Example: Double-click an element browser.element(name='new_user_button').double_click() """ self._element_call(lambda: ActionChains(self.driver).double_click(self.el) .perform(), self.wait_for_present) self.browser.after_hooks.run()
def right_click(self): """ Right clicks the element Note that browser support may vary :Example: Right click an element browser.element(name='new_user_button').right_click() """ self._element_call(lambda: ActionChains(self.driver).context_click(self.el) .perform(), self.wait_for_present) self.browser.after_hooks.run()
def hover(self): """ Moves the mouse to the middle of this element Note that browser support may vary :Example: Hover over an element browser.element(name='new_user_button').hover() """ self._element_call(lambda: ActionChains(self.driver).move_to_element(self.el) .perform(), self.wait_for_present) self.browser.after_hooks.run()
def hover(self, element): hover = ActionChains(self.browser).move_to_element(element) hover.perform()
def _reconcile_drag_preshot(self): ofxdiv = self.browser.find_element_by_id('ofx-2-0') logger.info('ofxdiv location: %s size: %s', ofxdiv.location, ofxdiv.size) pos_x = (ofxdiv.location['x'] - 400) + (ofxdiv.size['width'] / 4) pos_y = (ofxdiv.location['y'] - 50) + (ofxdiv.size['height'] / 2) self.browser.execute_script( "$('body').append($('%s'));" % self._cursor_script(pos_x, pos_y) ) actions = ActionChains(self.browser) actions.move_to_element(ofxdiv) actions.click_and_hold() actions.move_by_offset(-400, -50) actions.perform() self.browser.get_screenshot_as_file('docs/source/foo.png')
def __init__(self, url, webdriver, **kwargs): kwargs.setdefault('body', webdriver.page_source) kwargs.setdefault('encoding', 'utf-8') super(WebdriverResponse, self).__init__(url, **kwargs) self.actions = ActionChains(webdriver) self.webdriver = webdriver
def mouse_over(self, locator): """Moves the mouse pointer over the element found by the `locator`. :param locator: An instance of :class:`XPath` or a string containing an XPath expression. """ xpath = six.text_type(locator) el = self.find_element(xpath) actions = ActionChains(self.web_driver) actions.move_to_element(el) actions.perform()
def open_urls(self, urls, tab_limit=MAX_TABS): """ This works at least on Chrome across platforms. """ # First setup a document with the target URLs. link_doc = 'data:text/html,' link_doc += '<html><head><title>Links!</title></head><body>' id = 0 for url in urls: link_doc += '<a id="%d" href="%s">%d: %s</a><br>' % ( id, url, id, url) id += 1 link_doc += '</body><html>' self.driver.get(link_doc) # Now open each document in a new tab by ctrl+shift clicking the # anchor. for tag in self.driver.find_elements_by_tag_name("a"): action = ActionChains(self.driver) if mozinfo.os == "mac": ctrl_key = Keys.COMMAND else: ctrl_key = Keys.CONTROL action.key_down(ctrl_key).key_down(Keys.SHIFT).click( tag).key_up(Keys.SHIFT).key_up(ctrl_key).perform() time.sleep(self.per_tab_pause) time.sleep(self.settle_wait_time) self.stats.print_stats()
def drag_drop_test(driver, x_offset=0, y_offset=0, element_class="gt_slider_knob"): """???? :param x_offset:????x???? :param y_offset: ????y???? :param element_class: ???????css?? :return: """ dragger = driver.find_element_by_class_name(element_class) action = ActionChains(driver) action.drag_and_drop_by_offset(dragger, x_offset, y_offset).perform() time.sleep(2.8)
def click_element_at_coordinates(self, locator, xoffset, yoffset): """Click element identified by `locator` at x/y coordinates of the element. Cursor is moved and the center of the element and x/y coordinates are calculted from that point. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ self._info("Click clicking element '%s' in coordinates '%s', '%s'." % (locator, xoffset, yoffset)) element = self._element_find(locator, True, True) #self._element_find(locator, True, True).click() #ActionChains(self._current_browser()).move_to_element_with_offset(element, xoffset, yoffset).click().perform() ActionChains(self._current_browser()).move_to_element(element).move_by_offset(xoffset, yoffset).click().perform()
def double_click_element(self, locator): """Double click element identified by `locator`. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ self._info("Double clicking element '%s'." % locator) element = self._element_find(locator, True, True) ActionChains(self._current_browser()).double_click(element).perform()
def drag_and_drop(self, source, target): """Drags element identified with `source` which is a locator. Element can be moved on top of another element with `target` argument. `target` is a locator of the element where the dragged object is dropped. Examples: | Drag And Drop | elem1 | elem2 | # Move elem1 over elem2. | """ src_elem = self._element_find(source,True,True) trg_elem = self._element_find(target,True,True) ActionChains(self._current_browser()).drag_and_drop(src_elem, trg_elem).perform()
def drag_and_drop_by_offset(self, source, xoffset, yoffset): """Drags element identified with `source` which is a locator. Element will be moved by xoffset and yoffset, each of which is a negative or positive number specify the offset. Examples: | Drag And Drop By Offset | myElem | 50 | -35 | # Move myElem 50px right and 35px down. | """ src_elem = self._element_find(source, True, True) ActionChains(self._current_browser()).drag_and_drop_by_offset(src_elem, xoffset, yoffset).perform()
def mouse_over(self, locator): """Simulates hovering mouse over the element specified by `locator`. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ self._info("Simulating Mouse Over on element '%s'" % locator) element = self._element_find(locator, True, False) if element is None: raise AssertionError("ERROR: Element %s not found." % (locator)) ActionChains(self._current_browser()).move_to_element(element).perform()
def mouse_up(self, locator): """Simulates releasing the left mouse button on the element specified by `locator`. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ self._info("Simulating Mouse Up on element '%s'" % locator) element = self._element_find(locator, True, False) if element is None: raise AssertionError("ERROR: Element %s not found." % (locator)) ActionChains(self._current_browser()).release(element).perform()
def open_context_menu(self, locator): """Opens context menu on element identified by `locator`.""" element = self._element_find(locator, True, True) ActionChains(self._current_browser()).context_click(element).perform()
def mouse_down_on_link(self, locator): """Simulates a mouse down event on a link. Key attributes for links are `id`, `name`, `href` and link text. See `introduction` for details about locating elements. """ element = self._element_find(locator, True, True, 'link') ActionChains(self._current_browser()).click_and_hold(element).perform()
def mouse_down_on_image(self, locator): """Simulates a mouse down event on an image. Key attributes for images are `id`, `src` and `alt`. See `introduction` for details about locating elements. """ element = self._element_find(locator, True, True, 'image') ActionChains(self._current_browser()).click_and_hold(element).perform()